javaassertj

How do I check that no value is null after calling extracting on a list of objects?


Using AssertJ in a unit test, I want to extract several properties of a custom object from a list of such objects via extracting and check if they are all non-null.

For example, assuming I want to extract fieldA and fieldB of MyObject:

import static from org.assertj.core.api.Assertions.assertThat;

List<MyObject> theList = ...; 
assertThat(theList).extracting("fieldA", "fieldB")).isNotNull();

I am having trouble figuring out what is being checked.

Is isNotNull checking that:

  1. the iterable returned by extracting is not null?
  2. no tuples in the list are null?
  3. every value in every tuple is not null?

Solution

  • Following your example:

    assertThat(theList).extracting("fieldA", "fieldB").isNotNull();
    

    isNotNull only checks that the Iterable of tuples returned by extracting is not null.

    flatExtracting + doesNotContainNull

    To check that none of the extracted values are null, you can use flatExtracting and doesNotContainNull:

    assertThat(theList).flatExtracting("fieldA", "fieldB").doesNotContainNull();
    

    which yields a message like the following in case of failures:

    java.lang.AssertionError: 
    Expecting actual:
      ["value1", "value2", null, "value4"]
    not to contain null elements
    

    Due to the flattened nature of the solution, there is no indication of which object caused the failure but can be identified by counting the pairs in the displayed actual.

    extracting + noneMatch

    The complexity can be increased for clearer error messages:

    assertThat(theList).extracting("fieldA", "fieldB").noneMatch(tuple -> tuple.toList().contains(null));
    

    which yields in case of failure:

    java.lang.AssertionError: [Extracted: fieldA, fieldB] 
    Expecting no elements of:
      [("value1", "value2"), (null, "value4")]
    to match given predicate but this element did:
      (null, "value4")
    

    extracting + allSatisfy + doesNotContainNull

    Another option for clearer error messages:

    assertThat(theList).extracting("fieldA", "fieldB").allSatisfy(tuple -> assertThat(tuple.toList()).doesNotContainNull());
    

    which yields in case of failure:

    java.lang.AssertionError: [Extracted: fieldA, fieldB] 
    Expecting all elements of:
      [("value1", "value2"), (null, "value4")]
    to satisfy given requirements, but these elements did not:
    
    (null, "value4")
    error: 
    Expecting actual:
      [null, "value4"]
    not to contain null elements