5

I'm looking for a solution to check that each items in a collection have the field expectedNullField null.

The following doesn't work:

assertThat(aCollection).extracting("expectedNullField").isNull();

Note that the following works as expected: assertThat(aCollection).extracting("expectedNotNullField").isNotNull();

Anybody to help me ?

Thanks.

pierrefevrier
  • 1,570
  • 4
  • 22
  • 33

2 Answers2

7

If you know the size (let's say it is 3) you can use

assertThat(aCollection).extracting("expectedNullField")
                       .containsOnly(null, null, null);

or if you are only interested in checking that there is a null value

assertThat(aCollection).extracting("expectedNullField")
                       .containsNull();

Note that you can't use:

    assertThat(aCollection).extracting("expectedNullField")
                           .containsOnly(null);

because it is ambiguous (containsOnly specifying a varargs params).

I might consider adding containsOnlyNullElements() in AssertJ to overcome the compiler error above.

Joel Costigliola
  • 6,308
  • 27
  • 35
  • `assertThat(aCollection).extracting("expectedNullField").containsOnly(null);` is my favorite (because of readability), but it give me the following error (in addition to the compiler warning) `java.lang.NullPointerException: The array of values to look for should not be null` – pierrefevrier Mar 10 '17 at 13:19
  • 2
    that's because it tries to convert null to a varargs which is an array of value that should not be null. you could use it by casting null to the element collection type, ex: `assertThat(aCollection).extracting("stringField") .containsOnly((String)null);` – Joel Costigliola Mar 11 '17 at 21:30
0

You can use a Condition

Condition<YourClass> nullField = new Condition<>("expecting field to be null") {
  @Override
  public boolean matches(YourClass value) {
    return value.getField() == null;
  }
};

assertThat(aCollection).have(nullField);

which might be easier to read than the other solution

assertThat(aCollection).filteredOn("expectedNullField", not(null)).isEmpty();
Djon
  • 2,230
  • 14
  • 19