为什么没有“从不分配字段"?@Mock 警告

Why no quot;field is never assignedquot; warning with @Mock(为什么没有“从不分配字段?@Mock 警告)

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

问题描述

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

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;

警告消失并将该字段呈现为紫色以表明它已被分配.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

为方便起见,您还可以直接导航到这些设置,方法是在插入符号位于 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 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么没有“从不分配字段"?@Mock 警告

基础教程推荐