Search code examples
assertj

AssertJ check list contains X items but are all null


I've looked through the AssertJ examples (https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/IterableAssertionsExamples.java) but I can't find an example of: -

  1. assert list is of size X e.g. 3
  2. assert all items are null

e.g.

List<String> items= Arrays.asList(null, null, null);
assertThat(items).hasSize(3).containsOnlyNulls();

Note - containsOnlyNulls doesn't exist but this is essentially what I'm trying to test for. Can this be achieved in AssertJ?


Solution

  • You can use either

    // need to cast to String
    assertThat(items).hasSize(3).containsOnly((String) null);
    

    or

    assertThat(items).filteredOn(item -> item == null).hasSize(3);
    

    - Edit -

    containsOnlyNulls assertion has been added to AssertJ in 3.9.0+

    Example:

    // assertion will pass
    Iterable<String> items = Arrays.asList(null, null, null);
    assertThat(items).containsOnlyNulls();
    
    // assertion will fail because items2 contains a not null element
    Iterable<String> items2 = Arrays.asList(null, null, "notNull");
    assertThat(items2).containsOnlyNulls();
    
    // assertion will fail since an empty iterable does not contain any elements and therefore no null ones.
    Iterable<String> empty = new ArrayList<>();
    assertThat(empty).containsOnlyNulls();