问题描述
如果在测试类中声明私有字段:
If you declare a private field in a test class:
private Foo foo;
这已被使用,但从未分配,当我将鼠标悬停在声明上时,IntelliJ IDEA(可能还有其他IDE)会显示警告,并且将其呈现为灰色
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
私有字段"foo"从未分配
但是,如果我使用Mockito并像这样注释字段:
But if I'm using Mockito and annotate the field like:
@Mockprivate Foo foo;
@Mockprivate Foo foo;
警告消失,并以紫色显示该字段以表示已分配该字段. IDE如何知道@Mock
的含义?我浏览了Mockito源代码,注释定义似乎没有任何内容,我的IDE也没有Mockito插件.
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.
我正在编写一个类似于Mockito的带有等效注释的库,我很想知道让IDE删除警告.
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.
(我不是Java开发人员,所以如果我说错了,请纠正我)
(I'm not a Java developer, so if I've said anything wrong please correct me)
编辑我已经在Eclipse中进行了尝试,实际上它删除了带有任何批注的警告,这就是@nikpon的建议.
EDITI've tried this in Eclipse and it actually removes the warning with any annotation, which is what @nikpon was suggesting.
推荐答案
IntelliJ IDEA中的未使用符号"检查对此注释进行了特殊配置.
The "unused symbol" inspection in IntelliJ IDEA has special configuration for this annotation.
在 intellij-社区代码库显示了 JUnitEntryPoint 类,该类插入"deadCode"扩展点.
A quick search for "org.mockito.Mock" in the intellij-community code base reveals the JUnitEntryPoint class, which plugs into the "deadCode" extension point.
通过这种机制贡献的切入点依次由 UnusedDeclarationInspection .
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.
您可以从 Settings-> Inspections 访问此配置,然后按名称搜索未使用的符号"检查:未使用符号"检查配置的屏幕截图
You can access this configuration from Settings->Inspections, then search for the "unused symbol" inspection by name:screenshot of the "unused symbol" inspection configuration
为方便起见,您也可以直接输入以下设置,方法是:当插入符号位于IDEA标记为未使用的字段上时,调用 Alt-Enter :通过在未使用的字段上调用Alt-Enter来访问未使用的符号"设置的屏幕截图
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
这篇关于为什么没有“从不分配字段"? @Mock警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!