Skip to content

NPE in StandardRepresentation for maps with null entries #3087

@tkruse

Description

@tkruse

Describe the bug

When using a non-standard Java map where entries can be null, NPEs happen when assertJ tries to generate failure messages representing the map content.

Note that Map code allowing null map entries in .entrySet() are probably buggy, but I cannot tell if it really break a contract.

java.lang.NullPointerException
	at org.assertj.core.presentation.StandardRepresentation.toStringOf(StandardRepresentation.java:491)
	at org.assertj.core.presentation.StandardRepresentation.toStringOf(StandardRepresentation.java:236)
	at org.assertj.core.presentation.CompositeRepresentation.toStringOf(CompositeRepresentation.java:40)
        ...
  • assertj core version: 3.24.2
  • java version: 8
  • test framework version: Junit4
  • os (if relevant): Ubuntu

Test case reproducing the bug

To reproduce:

public class NullEntryMapTest {

    static class NullEntryMap<K, V> extends ConcurrentHashMap<K, V> {
        @Override
        public Set<Entry<K, V>> entrySet() {
            Set<Map.Entry<K, V>> set = new HashSet<>();
            set.add(null);
            return set;
        }
    }

    @Test
    public void testStandardRepresentationWithNullEntryMap() {
        StandardRepresentation.STANDARD_REPRESENTATION.toStringOf(new NullEntryMap<>());
    }

    @Test
    public void testContains() {
        assertThat(new NullEntryMap<>()).containsKey("foo"); // actual assertion does not matter
    }
}

To fix, StandardRepresentation should check the entry is not null.
It might be good to also check other occurences of entry.getKey() /entry.getValue() in the code.

I notice IntelliJ as an example handles this case in it's representation of maps.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions