Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no "field is never assigned" warning with @Mock

If you declare a private field in a test class:

private Foo foo;

That gets used but is never assigned, IntelliJ IDEA (and presumably other IDEs) show a warning when I hover over the declaration, and it renders it gray

private field 'foo' is never assigned

But if I'm using Mockito and annotate the field like:

@Mock private Foo foo;

The warning disappears and renders the field in purple to indicate that it is assigned. How does the IDE know what @Mock implies? I've had a look through the Mockito source code and there doesn't seem to be anything on the annotation definition and my IDE doesn't have a Mockito plugin.

I'm writing a library similar to Mockito with an equivilant annotation and I'd love to know to get the IDE to remove the warning.

(I'm not a Java developer, so if I've said anything wrong please correct me)

EDIT I've tried this in Eclipse and it actually removes the warning with any annotation, which is what @nikpon was suggesting.

like image 226
RichK Avatar asked Nov 01 '13 18:11

RichK


1 Answers

The "unused symbol" inspection in IntelliJ IDEA has special configuration for this annotation.

A quick search for "org.mockito.Mock" in the intellij-community code base reveals the JUnitEntryPoint class, which plugs into the "deadCode" extension point.

The entry points contributed through this mechanism are in turn queried by inspections like UnusedDeclarationInspection.

Note that the inspection has a configuration pane where you can configure additional custom annotations that should prevent a field from being marked as unused.

You can access this configuration from Settings->Inspections, then search for the "unused symbol" inspection by name: screenshot of the "unused symbol" inspection configuration

For convenience, you can also navigate to these settings directly, by invoking Alt-Enter while the caret is on a field marked as unused by IDEA: screenshot of accessing the "unused symbol" settings by invoking Alt-Enter on an unused field

like image 98
Pakka Pakka Avatar answered Nov 07 '22 23:11

Pakka Pakka