Skip to content

Commit

Permalink
Restore deep equality comparison for map containsOnly assertions (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
schlosna committed Jun 17, 2021
1 parent f8ee3f3 commit e3d9e07
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/main/java/org/assertj/core/internal/Maps.java
Original file line number Diff line number Diff line change
Expand Up @@ -486,20 +486,24 @@ private static <K, V> Map<K, V> mapWithoutExpectedEntries(Map<K, V> actual, Entr
// Stream API avoided for performance reasons
try {
Map<K, V> clonedMap = clone(actual);
for (Entry<? extends K, ? extends V> expectedEntry : expectedEntries) {
clonedMap.remove(expectedEntry.getKey(), expectedEntry.getValue());
}
removeEntries(clonedMap, expectedEntries);
return clonedMap;
} catch (NoSuchMethodException | UnsupportedOperationException e) {
// actual cannot be cloned or is unmodifiable, falling back to LinkedHashMap
Map<K, V> copiedMap = new LinkedHashMap<>(actual);
for (Entry<? extends K, ? extends V> expectedEntry : expectedEntries) {
copiedMap.remove(expectedEntry.getKey(), expectedEntry.getValue());
}
removeEntries(copiedMap, expectedEntries);
return copiedMap;
}
}

private static <K, V> void removeEntries(Map<K, V> map, Entry<? extends K, ? extends V>[] entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
// must perform deep equals comparison on values as Map.remove(Object, Object) relies on
// Objects.equals which does not handle deep equality (e.g. arrays in map entry values)
if (containsEntry(map, entry)) map.remove(entry.getKey());
}
}

public <K, V> void assertContainsExactly(AssertionInfo info, Map<K, V> actual, Entry<? extends K, ? extends V>[] entries) {
doCommonContainsCheck(info, actual, entries);
if (actual.isEmpty() && entries.length == 0) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,4 +243,14 @@ private static Stream<Arguments> orderDependentFailureTestCases() {
set(entry("name", "Yoda"), entry("job", "Jedi"))));
}

@SuppressWarnings("unchecked")
@Test
void should_pass_if_value_type_is_array() {
// GIVEN
Map<String, byte[]> actual = mapOf(entry("key1", new byte[] { 1, 2 }), entry("key2", new byte[] { 3, 4, 5 }));
Entry<String, byte[]>[] expected = new Entry[] { entry("key2", new byte[] { 3, 4, 5 }), entry("key1", new byte[] { 1, 2 }) };
// WHEN/THEN
assertThatNoException().isThrownBy(() -> maps.assertContainsOnly(info, actual, expected));
}

}

0 comments on commit e3d9e07

Please sign in to comment.