Skip to content

Commit

Permalink
Added tests for null-key edge cases of IsMapContaining.hasKey() and I…
Browse files Browse the repository at this point in the history
…sMapContaining.hasEntry()
  • Loading branch information
brownian-motion committed Apr 16, 2020
1 parent e4d21b1 commit 86a7bfa
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.hamcrest.Matcher;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

Expand Down Expand Up @@ -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<Number, String> 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<Number, String> 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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.hamcrest.Matcher;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

Expand Down Expand Up @@ -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<String, Integer> 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<String, Integer> 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<String, Integer> 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);
}
}

0 comments on commit 86a7bfa

Please sign in to comment.