Skip to content

Commit

Permalink
Handle null values in map entry sets when formatting
Browse files Browse the repository at this point in the history
If the map entry set contains a null value, print "null" instead of
throwing a NPE.

see: assertj#3087
  • Loading branch information
etellman committed Jul 16, 2023
1 parent c2d8586 commit a58ac87
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,14 @@ protected String toStringOf(Map<?, ?> map) {
builder.append(DEFAULT_MAX_ELEMENTS_EXCEEDED);
return builder.append("}").toString();
}
builder.append(format(map, entry.getKey())).append('=').append(format(map, entry.getValue()));

// the entry shouldn't be null in a valid map, but if it is, print it out gracefully instead of throwing a NPE
if (entry == null) {
builder.append("null");
} else {
builder.append(format(map, entry.getKey())).append('=').append(format(map, entry.getValue()));
}

printedElements++;
if (!entriesIterator.hasNext()) return builder.append("}").toString();
builder.append(", ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@
import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.Test;

/**
Expand Down Expand Up @@ -86,4 +90,18 @@ void should_retain_initial_ordering_if_keys_are_not_comparable() {

assertThat(STANDARD_REPRESENTATION.toStringOf(map)).isEqualTo("{\"foo\"=3, false=2, 'A'=1}");
}

@Test
void should_formal_null_in_the_entry_set() {
Map<Integer, Integer> map = new AbstractMap<Integer, Integer>() {
@Override
public Set<Entry<Integer, Integer>> entrySet() {
Set <Entry<Integer, Integer>> entries = new HashSet<>();
entries.add(null);
return entries;
}
};

assertThat(STANDARD_REPRESENTATION.toStringOf(map)).isEqualTo("{null}");
}
}

0 comments on commit a58ac87

Please sign in to comment.