assertj / doc

AssertJ new website

Home Page:https://assertj.github.io/doc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FeatureRequest: I wish there is a SoftAssertions.assertThat().isNotNullAndSatisfies( Consumer )

frankbenoit opened this issue · comments

When I want to verify fields in a nested object structure, SoftAssertions are cool, because they print out everything and do not stop on the first error.
However, when i access a field that can be null and want to go deeper, I need to write the field access twice or have a variable and "if". Non-fluent calls with repeating symbols:

var something = obj.getSomething();
softly.assertThat( something ).isNotNull();
if( something != null ){
    softly.assertthat(something.other()) ...; // (1)
}
... more tests on obj ...

The "if" is to avoid, when "something" is null, that it throws NPE in (1) and stops printing the remaining stuff.
The normal satisfies() does not check for isNotNull(), and even when .isNotNull() is chained with satisfies() as the consumer is called. Hence the access will throw NPE.

A bad workaround:

    static <T> void with(final SoftAssertions softly, final @Nullable T t, final Consumer<T> cons) {
        if (t == null) {
            softly.collectAssertionError(new AssertionError("t is null"));
        }
        else {
            cons.accept(t);
        }
    }

with(softly,  obj.getSomething(), something -> {
    softly.assertThat(something.other())
        .isEqualTo("x12");
});
softly.assertThat("asd")
    .isEqualTo("xxx");

The problem is, that it does not show the right location.
So I wish there would be a isNotNullAndSatisfies( Consumer ), which does the isNotNull() and only calls the consumer if the object is non-null:

softly.assertThat( obj.getSomething() )
    .isNotNullAndSatisfies( something -> {
        softly.assertThat(something.other())
            .isEqualTo("x12");
    });
softly.assertThat("asd")
    .isEqualTo("xxx");

Sorry, wrong location, i posted this to "core".