package org.hamcrest.collection; import static org.hamcrest.core.AllOf.allOf; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; import static org.hamcrest.core.IsEqual.equalTo; import java.util.Collection; import java.util.ArrayList; public class IsCollectionContaining extends TypeSafeMatcher> { private final Matcher elementMatcher; public IsCollectionContaining(Matcher elementMatcher) { this.elementMatcher = elementMatcher; } public boolean matchesSafely(Iterable collection) { for (T item : collection) { if (elementMatcher.matches(item)){ return true; } } return false; } public void describeTo(Description description) { description .appendText("a collection containing ") .appendDescriptionOf(elementMatcher); } @Factory public static Matcher> hasItem(Matcher elementMatcher) { return new IsCollectionContaining(elementMatcher); } @Factory public static Matcher> hasItem(T element) { return hasItem(equalTo(element)); } @Factory public static Matcher> hasItems(Matcher... elementMatchers) { Collection>> all = new ArrayList>>(elementMatchers.length); for (Matcher elementMatcher : elementMatchers) { all.add(hasItem(elementMatcher)); } return allOf(all); } @Factory public static Matcher> hasItems(T... elements) { Collection>> all = new ArrayList>>(elements.length); for (T element : elements) { all.add(hasItem(element)); } return allOf(all); } }