Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intellij IDEA warnings for @Nonnull annotation in unit tests

Let's say I have a method with some of the parameters annotated with javax @Nonnull annotation.

public Something supply(@Nonnull SomeObject someObject) {
    (...)
    if (someObject == null) throw new ValidationException("Required parameter is null");
    (...)
}

IDE correctly notifies me, when I try to call this method with explicit null argument, like this:

somethingSupplier.supply(null);

Now what I want to do is create unit test, that checks if proper exception will be thrown, if for some reason the argument passed to this method happens to be null (let's say it's some kind of validation exception).

If I try to call this method like in above example, IDE will warn me about passing null to @Nonnull... but this is exactly what I want to do here. I can annotate the call or the method or even the test class with @SuppressWarnings("ConstantConditions"), but it clutters the code and I might not get warned about other unintentional errors I make in code.

So the question is if I can somehow disable the inspection for @Nonnull in test classes? Or perhaps I shouldn't unit test those cases at all?

like image 995
mareckmareck Avatar asked Feb 09 '23 15:02

mareckmareck


1 Answers

If you want to test code behavior for erroneous cases, is it unavoidable to create code which is erroneous regarding the rules of the code under test. If these rules can be checked by an IDE, obviously, these checks will detect that and suppressing these warnings is unavoidable.

As always with suppressing warnings, you should try to narrow the code for which the suppressing applies as much as possible. E.g., you can create a factory method within the testing code providing such an illegal value which flies under the radar of the type system based check:

class IllegalValue {
    @SuppressWarnings("ConstantConditions")
    static @Nonnull <T> T sneakyNullReference() {
        return null;
    }
}

That way you have limited the suppressing to this small single method. Within your test cases you may use IllegalValue.sneakyNullReference() for testing code for its null behavior without additional suppression and hence rightly getting warnings when using null at inappropriate places within the test code. I strongly recommend to never store the result of sneakyNullReference() into a variable but always reference directly where needed, for clarity.

I.e. within the test of your question the code should look like

somethingSupplier.supply(IllegalValue.sneakyNullReference());

so a reader immediately understands what is tested here…

like image 84
Holger Avatar answered Feb 12 '23 07:02

Holger