|
| 1 | +package org.hamcrest.collection; |
| 2 | + |
| 3 | +import static org.hamcrest.core.AnyOf.anyOf; |
| 4 | +import static org.hamcrest.core.IsEqual.equalTo; |
| 5 | + |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.Collection; |
| 8 | + |
| 9 | +import org.hamcrest.Description; |
| 10 | +import org.hamcrest.Factory; |
| 11 | +import org.hamcrest.Matcher; |
| 12 | +import org.hamcrest.TypeSafeMatcher; |
| 13 | + |
| 14 | +/** |
| 15 | + * Matches collections that only contain elements that satisfy a given matcher. |
| 16 | + * </p> |
| 17 | + * For example <pre>[1,2,3]</pre> satisfies onlyContains(lessThan(4)) |
| 18 | + * |
| 19 | + * @author ngd |
| 20 | + */ |
| 21 | +public class IsCollectionOnlyContaining<T> extends TypeSafeMatcher<Collection<T>> { |
| 22 | + |
| 23 | + private final Matcher<T> matcher; |
| 24 | + |
| 25 | + public IsCollectionOnlyContaining(Matcher<T> matcher) { |
| 26 | + this.matcher = matcher; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public boolean matchesSafely(Collection<T> items) { |
| 31 | + for (T item : items) { |
| 32 | + if (!matcher.matches(item)) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + } |
| 36 | + return true; |
| 37 | + } |
| 38 | + |
| 39 | + public void describeTo(Description description) { |
| 40 | + description |
| 41 | + .appendText("a collection containing items matching ") |
| 42 | + .appendDescriptionOf(matcher); |
| 43 | + } |
| 44 | + |
| 45 | + @Factory |
| 46 | + public static <T> Matcher<Collection<T>> onlyContains(T... items) { |
| 47 | + Collection<Matcher<T>> matchers = new ArrayList<Matcher<T>>(); |
| 48 | + for (T item : items) { |
| 49 | + matchers.add(equalTo(item)); |
| 50 | + } |
| 51 | + return new IsCollectionOnlyContaining<T>(anyOf(matchers)); |
| 52 | + } |
| 53 | + |
| 54 | + @Factory |
| 55 | + public static <T> Matcher<Collection<T>> onlyContains(Matcher<T>... matchers) { |
| 56 | + return new IsCollectionOnlyContaining<T>(anyOf(matchers)); |
| 57 | + } |
| 58 | +} |
0 commit comments