11package org .hamcrest .collection ;
22
33import org .hamcrest .Description ;
4+ import org .hamcrest .Factory ;
45import org .hamcrest .Matcher ;
6+ import static org .hamcrest .core .IsAnything .anything ;
7+ import static org .hamcrest .core .IsEqual .eq ;
58
6- import java .util .Iterator ;
79import java .util .Map ;
810import java .util .Map .Entry ;
911
10- public class IsMapContaining implements Matcher {
11- private final Matcher keyMatcher ;
12- private final Matcher valueMatcher ;
12+ public class IsMapContaining <K ,V > implements Matcher <Map <K , V >> {
1313
14- public IsMapContaining (Matcher keyMatcher , Matcher valueMatcher ) {
14+ private final Matcher <K > keyMatcher ;
15+ private final Matcher <V > valueMatcher ;
16+
17+ public IsMapContaining (Matcher <K > keyMatcher , Matcher <V > valueMatcher ) {
1518 this .keyMatcher = keyMatcher ;
1619 this .valueMatcher = valueMatcher ;
1720 }
1821
19- public boolean match (Object o ) {
20- if (o != null && o instanceof Map ) {
21- Map map = (Map ) o ;
22-
23- for (Iterator i = map .entrySet ().iterator (); i .hasNext ();) {
24- Map .Entry entry = (Entry ) i .next ();
25-
26- if (keyMatcher .match (entry .getKey ()) && valueMatcher .match (entry .getValue ())) {
27- return true ;
28- }
22+ public boolean match (Map <K , V > map ) {
23+ if (map == null ) {
24+ return false ;
25+ }
26+ for (Entry <K , V > entry : map .entrySet ()) {
27+ if (keyMatcher .match (entry .getKey ()) && valueMatcher .match (entry .getValue ())) {
28+ return true ;
2929 }
3030 }
31-
3231 return false ;
3332 }
3433
@@ -39,4 +38,35 @@ public void describeTo(Description description) {
3938 valueMatcher .describeTo (description );
4039 description .appendText ("]" );
4140 }
41+
42+ @ Factory
43+ public static <K ,V > Matcher <Map <K ,V >> mapContaining (Matcher <K > keyMatcher , Matcher <V > valueMatcher ) {
44+ return new IsMapContaining <K ,V >(keyMatcher , valueMatcher );
45+ }
46+
47+ @ Factory
48+ public static <K ,V > Matcher <Map <K ,V >> mapContaining (K key , V value ) {
49+ return mapContaining (eq (key ), eq (value ));
50+ }
51+
52+ @ Factory
53+ public static <K ,V > Matcher <Map <K ,V >> mapWithKey (Matcher <K > keyMatcher ) {
54+ return mapContaining (keyMatcher , (Matcher <V >)anything ());
55+ }
56+
57+ @ Factory
58+ public static <K ,V > Matcher <Map <K ,V >> mapWithKey (K key ) {
59+ return mapWithKey (eq (key ));
60+ }
61+
62+ @ Factory
63+ public static <K ,V > Matcher <Map <K ,V >> mapWithValue (Matcher <V > valueMatcher ) {
64+ return mapContaining ((Matcher <K >)anything (), valueMatcher );
65+ }
66+
67+ @ Factory
68+ public static <K ,V > Matcher <Map <K ,V >> mapWithValue (V value ) {
69+ return mapWithValue (eq (value ));
70+ }
71+
4272}
0 commit comments