junit5 icon indicating copy to clipboard operation
junit5 copied to clipboard

`Assertions.assertNotNull()` should return the non-null object

Open garydgregory opened this issue 1 year ago • 8 comments

As a developer, I like to write some test code like:

import static org.junit.jupiter.api.Assertions.assertNotNull;
...
Foo foo = assertNotNull(bar.doSomething()).getFoo();

Deliverables

  • An Assertions.assertNotNull() that returns its input and not void.
  • You could make the same argument for assertSame()

garydgregory avatar Sep 20 '24 18:09 garydgregory

If using AssertJ is an option, with version 3.27.0 it will be possible to write the following:

import static org.assertj.core.api.Assertions.assertThat;
...
Foo foo = assertThat(bar.doSomething()).isNotNull().actual().getFoo();

See assertj/assertj#3489.

scordio avatar Sep 20 '24 18:09 scordio

Hello @scordio

Thank you for your reply.

I'll be honest with you: I'll never write this kind of extra verbose code. I feel that this obfuscates what the test is trying to show.

The reason I gave this example is because I want less code, not more ;-) I'll stick with the straightforward for now :)

garydgregory avatar Sep 20 '24 18:09 garydgregory

Totally understandable 😉 a pure non-null assertion is not the best showcase for that, but users find it handy for more complex use cases.

As with everything, YMMV 🙂

scordio avatar Sep 20 '24 19:09 scordio

And do I have miles! 😜

garydgregory avatar Sep 20 '24 21:09 garydgregory

Changing the result type of assertNotNull would break backward (binary) compatibility. You could use java.util.Objects.requireNonNull instead.

marcphilipp avatar Sep 21 '24 09:09 marcphilipp

I agree BC is key, this would be for 6.0. Nice idea using requireNonNull 👍

garydgregory avatar Sep 21 '24 10:09 garydgregory

The assertNotNull is verbose and superfluous. Just write Foo foo = bar.doSomething().getFoo(); and Helpful NullPointerExceptions show the null cause.

bjmi avatar Oct 05 '24 19:10 bjmi

The assertNotNull is verbose and superfluous. Just write Foo foo = bar.doSomething().getFoo(); and Helpful NullPointerExceptions show the null cause.

Hello @bjmi JEP 358 is irrelevant here since it requires Java 14 or above. It is a great improvement though! 👍

garydgregory avatar Oct 05 '24 19:10 garydgregory

Team decision: Since JUnit 6 requires Java 17, we recommend just writing bar.doSomething().getFoo() from now on or using requireNonNull to avoid any nullability-related IDE/compiler warnings/errors.

marcphilipp avatar Jul 11 '25 13:07 marcphilipp