|
| 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 arrays where all elements satisfy the specified matcher. |
| 16 | + * This is the array equivalent of {@link IsCollectionOnlyContaining} |
| 17 | + * |
| 18 | + * @author ngd |
| 19 | + */ |
| 20 | +public class IsArrayOnlyContaining<T> extends TypeSafeMatcher<T[]> { |
| 21 | + |
| 22 | + private final Matcher<T> matcher; |
| 23 | + |
| 24 | + public IsArrayOnlyContaining(Matcher<T> matcher) { |
| 25 | + this.matcher = matcher; |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public boolean matchesSafely(T[] items) { |
| 30 | + if (items.length == 0) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + for (T item : items) { |
| 34 | + if (!matcher.matches(item)) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + public void describeTo(Description description) { |
| 42 | + description |
| 43 | + .appendText("is array containing items matching ") |
| 44 | + .appendDescriptionOf(matcher); |
| 45 | + } |
| 46 | + |
| 47 | + @Factory |
| 48 | + public static <T> Matcher<T[]> isArrayOnlyContaining(T...items) { |
| 49 | + Collection<Matcher<T>> matchers = new ArrayList<Matcher<T>>(); |
| 50 | + for (T item : items) { |
| 51 | + matchers.add(equalTo(item)); |
| 52 | + } |
| 53 | + return new IsArrayOnlyContaining<T>(anyOf(matchers)); |
| 54 | + } |
| 55 | + |
| 56 | + @Factory |
| 57 | + public static <T> Matcher<T[]> isArrayOnlyContaining(Matcher<T>...matchers) { |
| 58 | + return new IsArrayOnlyContaining<T>(anyOf(matchers)); |
| 59 | + } |
| 60 | +} |
0 commit comments