FindBugs Ignores @Nullable

2.3k views Asked by At

I have a unit test where I deliberately pass a null parameter to a method, to verify that the method correctly detects the null. I added the @Nullable annotation to the parameter, but FindBugs complains that the (deliberate) null argument is an error. Here's the code:

@Test(expected = ApiDataError.class) public void dateNull() {
    try {
        @Nullable final Date date = null;
        ApiFault.check(date, TEST);
    } catch (final ApiDataError ex) {
        assertEquals(ex.getMessage(), format(ApiFault.NULL_VALUE, TEST));
        throw ex;
    }
}

FindBugs reports:

Bug: Non-virtual method call in com.foo.test.ex.ApiFaultTests.dateNull() passes null for nonnull parameter of com.foo.commons.ex.error.ApiFault.check(Date, String)

How can I make FindBugs stop crying wolf?

I use Eclipse Kepler, service release 2, with FindBugs 3.00.

2

There are 2 answers

3
dnault On

Use an exclusion filter to tell FindBugs not to report the error when analyzing your unit test class. Your filter might look something like this:

<FindBugsFilter>
    <!-- Passing null is deliberate in this unit test-->
    <Match>
        <Class name="com.foo.test.ex.ApiFaultTests" />
        <Method name="dateNull" />
        <Bug code="NP" />
    </Match>
</FindBugsFilter>
1
barfuin On

Reading the other posts for this question, I assume that your method under test expects the parameter to be non-null, but you want to pass null as part of this one unit test.

In that case, you can simply annotate the unit test method with @SuppressFBWarnings:

@SuppressFBWarnings(value="NP_NONNULL_PARAM_VIOLATION",
    justification="testing nullness contract violation")
@Test(expected = ApiDataError.class)
public void dateNull() throws ApiDataError {
    final Date date = null;
    ApiFault.check(date, TEST);
}