Assertj verify that a field of each items in a collection is always null
Asked Answered
P

2

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.

Personate answered 9/3, 2017 at 10:53 Comment(3)
How about assertThat(aCollection).filteredOn("expectedNullField", not(null)).isEmpty();Davidson
It works but it's not easy to read :SPersonate
Then I would use Conditions joel-costigliola.github.io/assertj/assertj-core-conditions.html, it's more verbose but easier to readDavidson
Y
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.

Yingling answered 9/3, 2017 at 20:50 Comment(2)
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 nullPersonate
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);Yingling
D
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();
Davidson answered 9/3, 2017 at 11:20 Comment(5)
It doesn't work: java.lang.NullPointerException: The array of values to look for should not be nullPersonate
Back to Conditions then I guess :(Davidson
Maybe the fact that assertThat(aCollection).extracting("expectedNullField").isNull(); doesn't work as I expect it to is a bug ?Personate
My understanding is that it would check the collection and not its elements. Which version are you using?Davidson
I'm using version 2.5.0 (the one that Spring Boot uses)Personate

© 2022 - 2024 — McMap. All rights reserved.