Unit test entry for annotated @Nonnull parameter

I have a method like this:

 public void foo(@Nonnull String value) {...}

I would like to write unit test to make sure that it foo()throws NPE when valueis null, but I can not, because the compiler refuses to compile unit test when analyzing the flow of static null pointers enabled in the IDE.

How to make this test compiler (in Eclipse with "Enable annotation-based zero analysis" enabled):

@Test(expected = NullPointerException.class)
public void test() {
     T inst = ...
     inst.foo(null);
}

Note. Theoretically, a static compiler null pointer should prevent such cases. But there is nothing that would prevent someone from writing another module with the static flow analysis turned off and the method nullcalled with .

: . . , , , .

, , . , .

: , ", " ( , , ... ). , , , , @Nonnull?

+4
4

null :

public void foo(@NonNull String bar) {
    Objects.requireNonNull(bar);
}

/** Trick the Java flow analysis to allow passing <code>null</code>
 *  for @Nonnull parameters. 
 */
@SuppressWarnings("null")
public static <T> T giveNull() {
    return null;
}

@Test(expected = NullPointerException.class)
public void testFoo() {
    foo(giveNull());
}

( , - foo(null) IDE , " " ).

, , (, , Java8 ).

, ( ) , Objects.requireNonNull().

+4

?

try {
    YourClass.getMethod("foo", String.class).invoke(someInstance, null);
    fail("Expected InvocationException with nested NPE");
} catch(InvocationException e) {
    if (e.getCause() instanceof NullPointerException) {
        return; // success
    }
    throw e; // let the test fail
}

, ( , , ).

+2

. null value , notNull.

0

You can use the field that you initialize, and then set nullin the configuration method:

private String nullValue = ""; // set to null in clearNullValue()
@Before
public void clearNullValue() {
    nullValue = null;
}

@Test(expected = NullPointerException.class)
public void test() {
     T inst = ...
     inst.foo(nullValue);
}

As in GhostCat's answer, the compiler cannot find out if and when it is called clearNullValue(), and must assume that this field is not null.

0
source

Source: https://habr.com/ru/post/1683741/


All Articles