为什么没有“永远不会分配字段"?警告@Mock [英] Why no "field is never assigned" warning with @Mock

查看:35
本文介绍了为什么没有“永远不会分配字段"?警告@Mock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在测试类中声明私有字段:

If you declare a private field in a test class:

私有 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:

@Mock私人 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 所建议的.

EDIT I'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- 中快速搜索org.mockito.Mock"社区 代码库揭示了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

为方便起见,您还可以通过调用 Alt-Enter 直接导航到这些设置,同时插入符号位于 IDEA 标记为未使用的字段上:通过在未使用的字段上调用 ​​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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆