简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM