diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java index 66876d0d..1dc347e6 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java @@ -4,6 +4,7 @@ import org.hamcrest.Matcher; import java.util.HashMap; +import java.util.Hashtable; import java.util.Map; import java.util.TreeMap; @@ -62,7 +63,25 @@ public void testMatchesMapContainingKeyWithNumberKeys() throws Exception { assertThat(map, hasKey((Number)1)); // TODO: work out the correct sprinkling of wildcards to get this to work! -// assertThat(map, hasKey(1)); + // assertThat(map, hasKey(1)); + } + + public void test_mapContainingNullKey_returnsFalse_forMapsWithNonnullKeys() throws Exception { + Map map = new Hashtable<>(); // Hashtables cannot store null keys + map.put(1, "A"); + map.put(2, "B"); + + assertDoesNotMatch(hasKey((Number)null), map); + } + + + public void test_mapContainingNullKey_returnsTrue_forMapWithNullKey() throws Exception { + Map map = new HashMap<>(); // HashMap can store null keys + map.put(1, "A"); + map.put(2, "B"); + map.put(null, "C"); + + assertMatches(hasKey((Number)null), map); } public void testHasReadableDescription() { diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java index 3eed3463..2d0fd937 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java @@ -4,6 +4,7 @@ import org.hamcrest.Matcher; import java.util.HashMap; +import java.util.Hashtable; import java.util.Map; import java.util.TreeMap; @@ -46,4 +47,29 @@ public void testDoesNotMatchNull() { public void testHasReadableDescription() { assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2)))); } + + public void test_mapContainsEntryWithNullKey_returnsFalseForMapsWithoutNullKeys(){ + Map map = new Hashtable<>(); // throws exception if given null key, or if map.containsKey(null) is called + map.put("a", 1); + map.put("b", 2); + + assertDoesNotMatch(hasEntry(null, 2), map); + } + + public void test_mapContainsEntryWithNullKey_returnsTrueForMapWithNullKeyAndMatchingValue(){ + Map map = new HashMap<>(); // throws exception if given null key, or if map.containsKey(null) is called + map.put("a", 1); + map.put("b", 2); + map.put(null, 3); + + assertMatches(hasEntry(null, 3), map); + } + + public void test_mapContainsEntryWithNullKey_returnsFalseForMapWithNullKeyAndNoMatchingValue(){ + Map map = new HashMap<>(); // throws exception if given null key, or if map.containsKey(null) is called + map.put("a", 1); + map.put("b", 2); + + assertDoesNotMatch(hasEntry(null, 3), map); + } }