package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; public class CombinableMatcher extends TypeSafeDiagnosingMatcher { private final Matcher matcher; public CombinableMatcher(Matcher matcher) { this.matcher = matcher; } @Override protected boolean matchesSafely(T item, Description mismatch) { if (!matcher.matches(item)) { matcher.describeMismatch(item, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendDescriptionOf(matcher); } public CombinableMatcher and(Matcher other) { return new CombinableMatcher(new AllOf(templatedListWith(other))); } public CombinableMatcher or(Matcher other) { return new CombinableMatcher(new AnyOf(templatedListWith(other))); } private ArrayList> templatedListWith(Matcher other) { ArrayList> matchers = new ArrayList>(); matchers.add(matcher); matchers.add(other); return matchers; } /** * Creates a matcher that matches when both of the specified matchers match the examined object. * For example: *
assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ public static CombinableBothMatcher both(Matcher matcher) { return new CombinableBothMatcher(matcher); } public static final class CombinableBothMatcher { private final Matcher first; public CombinableBothMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher and(Matcher other) { return new CombinableMatcher(first).and(other); } } /** * Creates a matcher that matches when either of the specified matchers match the examined object. * For example: *
assertThat("fan", either(containsString("a")).or(containsString("b")))
*/ public static CombinableEitherMatcher either(Matcher matcher) { return new CombinableEitherMatcher(matcher); } public static final class CombinableEitherMatcher { private final Matcher first; public CombinableEitherMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher or(Matcher other) { return new CombinableMatcher(first).or(other); } } }