1 package org.hamcrest.core; 2 3 import org.hamcrest.Description; 4 import org.hamcrest.DiagnosingMatcher; 5 import org.hamcrest.Matcher; 6 7 import java.util.Arrays; 8 import java.util.List; 9 10 /** 11 * Calculates the logical conjunction of multiple matchers. Evaluation is shortcut, so 12 * subsequent matchers are not called if an earlier matcher returns <code>false</code>. 13 */ 14 public class AllOf<T> extends DiagnosingMatcher<T> { 15 16 private final Iterable<Matcher<? super T>> matchers; 17 AllOf(Iterable<Matcher<? super T>> matchers)18 public AllOf(Iterable<Matcher<? super T>> matchers) { 19 this.matchers = matchers; 20 } 21 22 @Override matches(Object o, Description mismatch)23 public boolean matches(Object o, Description mismatch) { 24 for (Matcher<? super T> matcher : matchers) { 25 if (!matcher.matches(o)) { 26 mismatch.appendDescriptionOf(matcher).appendText(" "); 27 matcher.describeMismatch(o, mismatch); 28 return false; 29 } 30 } 31 return true; 32 } 33 34 @Override describeTo(Description description)35 public void describeTo(Description description) { 36 description.appendList("(", " " + "and" + " ", ")", matchers); 37 } 38 39 /** 40 * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. 41 * For example: 42 * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> 43 */ allOf(Iterable<Matcher<? super T>> matchers)44 public static <T> Matcher<T> allOf(Iterable<Matcher<? super T>> matchers) { 45 return new AllOf<>(matchers); 46 } 47 48 /** 49 * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. 50 * For example: 51 * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> 52 */ 53 @SafeVarargs allOf(Matcher<? super T>.... matchers)54 public static <T> Matcher<T> allOf(Matcher<? super T>... matchers) { 55 return allOf((List) Arrays.asList(matchers)); 56 } 57 } 58