java - Writing unit test for @Nonnull annotated parameter -
i have method one:
public void foo(@nonnull string value) {...}
i write unit test make sure foo()
throws npe when value
null
can't since compiler refuses compile unit test when static null pointer flow analysis enabled in ide.
how make test compile (in eclipse "enable annotation-based null analysis" enabled):
@test(expected = nullpointerexception.class) public void test() { t inst = ... inst.foo(null); }
note: in theory static null pointer of compiler should prevent cases that. there nothing stopping writing module static flow analysis turned off , calling method null
.
common case: big messy old project without flow analysis. start annotating utility module. in case, i'll have existing or new unit tests check how code behaves modules don't use flow analysis yet.
my guess have move tests unchecked module , move them around spread flow analysis. work , fit philosophy lot of manual work.
to put way: can't write test says "success when code doesn't compile" (i'd have put code pieces files, invoke compiler unit tests, check output errors ... not pretty). how can test easily code fails should when callers ignore @nonnull
?
hiding null
within method trick:
public void foo(@nonnull string bar) { objects.requirenonnull(bar); } /** trick java flow analysis allow passing <code>null</code> * @nonnull parameters. */ @suppresswarnings("null") public static <t> t givenull() { return null; } @test(expected = nullpointerexception.class) public void testfoo() { foo(givenull()); }
the above compiles fine (and yes, double-checked - when using foo(null)
ide gives me compile error - "null checking" enabled).
in contrast solution given via comments, above has nice side effect work any kind of parameter type (but might require java8 type inference correct always).
and yes, test passes (as written above), , fails when commenting out objects.requirenonnull()
line.
Comments
Post a Comment