File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed
hamcrest/src/test/java/org/hamcrest/collection Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change 44import org .hamcrest .Matcher ;
55
66import java .util .HashMap ;
7+ import java .util .Hashtable ;
78import java .util .Map ;
89import java .util .TreeMap ;
910
@@ -62,7 +63,25 @@ public void testMatchesMapContainingKeyWithNumberKeys() throws Exception {
6263 assertThat (map , hasKey ((Number )1 ));
6364
6465 // TODO: work out the correct sprinkling of wildcards to get this to work!
65- // assertThat(map, hasKey(1));
66+ // assertThat(map, hasKey(1));
67+ }
68+
69+ public void test_mapContainingNullKey_returnsFalse_forMapsWithNonnullKeys () throws Exception {
70+ Map <Number , String > map = new Hashtable <>(); // Hashtables cannot store null keys
71+ map .put (1 , "A" );
72+ map .put (2 , "B" );
73+
74+ assertDoesNotMatch (hasKey ((Number )null ), map );
75+ }
76+
77+
78+ public void test_mapContainingNullKey_returnsTrue_forMapWithNullKey () throws Exception {
79+ Map <Number , String > map = new HashMap <>(); // HashMap can store null keys
80+ map .put (1 , "A" );
81+ map .put (2 , "B" );
82+ map .put (null , "C" );
83+
84+ assertMatches (hasKey ((Number )null ), map );
6685 }
6786
6887 public void testHasReadableDescription () {
Original file line number Diff line number Diff line change 44import org .hamcrest .Matcher ;
55
66import java .util .HashMap ;
7+ import java .util .Hashtable ;
78import java .util .Map ;
89import java .util .TreeMap ;
910
@@ -46,4 +47,29 @@ public void testDoesNotMatchNull() {
4647 public void testHasReadableDescription () {
4748 assertDescription ("map containing [\" a\" -><2>]" , hasEntry (equalTo ("a" ), (equalTo (2 ))));
4849 }
50+
51+ public void test_mapContainsEntryWithNullKey_returnsFalseForMapsWithoutNullKeys (){
52+ Map <String , Integer > map = new Hashtable <>(); // throws exception if given null key, or if map.containsKey(null) is called
53+ map .put ("a" , 1 );
54+ map .put ("b" , 2 );
55+
56+ assertDoesNotMatch (hasEntry (null , 2 ), map );
57+ }
58+
59+ public void test_mapContainsEntryWithNullKey_returnsTrueForMapWithNullKeyAndMatchingValue (){
60+ Map <String , Integer > map = new HashMap <>(); // throws exception if given null key, or if map.containsKey(null) is called
61+ map .put ("a" , 1 );
62+ map .put ("b" , 2 );
63+ map .put (null , 3 );
64+
65+ assertMatches (hasEntry (null , 3 ), map );
66+ }
67+
68+ public void test_mapContainsEntryWithNullKey_returnsFalseForMapWithNullKeyAndNoMatchingValue (){
69+ Map <String , Integer > map = new HashMap <>(); // throws exception if given null key, or if map.containsKey(null) is called
70+ map .put ("a" , 1 );
71+ map .put ("b" , 2 );
72+
73+ assertDoesNotMatch (hasEntry (null , 3 ), map );
74+ }
4975}
You can’t perform that action at this time.
0 commit comments