package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsAnything; import static org.hamcrest.core.IsEqual.equalTo; import java.util.Map; import java.util.Map.Entry; public class IsMapContaining extends TypeSafeMatcher> { private final Matcher keyMatcher; private final Matcher valueMatcher; public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) { this.keyMatcher = keyMatcher; this.valueMatcher = valueMatcher; } public boolean matchesSafely(Map map) { for (Entry entry : map.entrySet()) { if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) { return true; } } return false; } public void describeTo(Description description) { description.appendText("map containing [") .appendDescriptionOf(keyMatcher) .appendText("->") .appendDescriptionOf(valueMatcher) .appendText("]"); } @Factory public static Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) { return new IsMapContaining(keyMatcher, valueMatcher); } @Factory public static Matcher> hasEntry(K key, V value) { return hasEntry(equalTo(key), equalTo(value)); } @Factory public static Matcher> hasKey(Matcher keyMatcher) { return hasEntry(keyMatcher, IsAnything.anything()); } @Factory public static Matcher> hasKey(K key) { return hasKey(equalTo(key)); } @Factory public static Matcher> hasValue(Matcher valueMatcher) { return hasEntry(IsAnything.anything(), valueMatcher); } @Factory public static Matcher> hasValue(V value) { return hasValue(equalTo(value)); } }