All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hamcrest.Condition Maven / Gradle / Ivy

There is a newer version: 4.0.2
Show newest version
package org.hamcrest;

/**
 * A Condition implements part of a multi-step match. We sometimes need to write matchers
 * that have a sequence of steps, where each step depends on the result of the previous
 * step and we can stop processing as soon as a step fails. These classes provide
 * infrastructure for writing such a sequence.
 *
 * Based on https://github.com/npryce/maybe-java
 * @author Steve Freeman 2012 http://www.hamcrest.com
 */

public abstract class Condition {
    public static final NotMatched NOT_MATCHED = new NotMatched();

    public interface Step {
        Condition apply(I value, Description mismatch);
    }

    private Condition() { }

    public abstract boolean matching(Matcher match, String message);
    public abstract  Condition and(Step mapping);

    public final boolean matching(Matcher match) { return matching(match, ""); }
    public final  Condition then(Step mapping) { return and(mapping); }

    @SuppressWarnings("unchecked")
    public static  Condition notMatched() {
        return (Condition) NOT_MATCHED;
    }

    public static  Condition matched(final T theValue, final Description mismatch) {
        return new Matched(theValue, mismatch);
    }

    private static final class Matched extends Condition {
        private final T theValue;
        private final Description mismatch;

        private Matched(T theValue, Description mismatch) {
            this.theValue = theValue;
            this.mismatch = mismatch;
        }

        @Override
        public boolean matching(Matcher matcher, String message) {
            if (matcher.matches(theValue)) {
                return true;
            }
            mismatch.appendText(message);
            matcher.describeMismatch(theValue, mismatch);
            return false;
        }

        @Override
        public  Condition and(Step next) {
            return next.apply(theValue, mismatch);
        }
    }

    private static final class NotMatched extends Condition {
        @Override public boolean matching(Matcher match, String message) { return false; }

        @Override public  Condition and(Step mapping) {
            return notMatched();
        }
    }
}