assertj / assertj/assertj

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

Open
#2,486 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
2.8k
Forks
788
Avg merge
14h 57m
Merged PRs (30d)
36

Description

#### Summary
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:
````java
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.

#### Example

A workaround:
````java
public static Consumer notNullFilter(final Consumer consumer) {
return t -> {
if (t != null) {
consumer.accept(t);
}
};
}
softly.assertThat( obj.getSomething() )
.isNotNull()
.satisfies( notNullFilter( something -> {
softly.assertThat(something.other())
.isEqualTo("x12");
}));
softly.assertThat("asd")
.isEqualTo("xxx");
````
That is near to what I want, but if the .isNotNull() call is forgotten, the block is silently not tested.

So I wish there would be a isNotNullAndSatisfies( Consumer ), which does the isNotNull() and only calls the consumer if the object is non-null:
````java
softly.assertThat( obj.getSomething() )
.isNotNullAndSatisfies( something -> {
softly.assertThat(something.other())
.isEqualTo("x12");
});
softly.assertThat("asd")
.isEqualTo("xxx");
````

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.