Home | History | Annotate | Download | only in core
      1 package org.hamcrest.core;
      2 
      3 import org.hamcrest.Description;
      4 import org.hamcrest.Matcher;
      5 import org.hamcrest.TypeSafeDiagnosingMatcher;
      6 
      7 public class Every<T> extends TypeSafeDiagnosingMatcher<Iterable<? extends T>> {
      8     private final Matcher<? super T> matcher;
      9 
     10     public Every(Matcher<? super T> matcher) {
     11         this.matcher= matcher;
     12     }
     13 
     14     @Override
     15     public boolean matchesSafely(Iterable<? extends T> collection, Description mismatchDescription) {
     16         for (T t : collection) {
     17             if (!matcher.matches(t)) {
     18                 mismatchDescription.appendText("an item ");
     19                 matcher.describeMismatch(t, mismatchDescription);
     20                 return false;
     21             }
     22         }
     23         return true;
     24     }
     25 
     26     @Override
     27     public void describeTo(Description description) {
     28         description.appendText("every item is ").appendDescriptionOf(matcher);
     29     }
     30 
     31     /**
     32      * Creates a matcher for {@link Iterable}s that only matches when a single pass over the
     33      * examined {@link Iterable} yields items that are all matched by the specified
     34      * <code>itemMatcher</code>.
     35      * For example:
     36      * <pre>assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))</pre>
     37      *
     38      * @param itemMatcher
     39      *     the matcher to apply to every item provided by the examined {@link Iterable}
     40      */
     41     public static <U> Matcher<Iterable<? extends U>> everyItem(final Matcher<U> itemMatcher) {
     42         return new Every<U>(itemMatcher);
     43     }
     44 }
     45