Junit @Rule 和 Maven Checkstyle 插件
Junit @Rule and Maven Checkstyle Plugin
Junit @Rules and maven-checkstyle-plugin 似乎彼此不和
如果 @Rule
是 private
或包私有那么结果是:
java.lang.Exception: The @Rule 'someRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError
但是如果 @Rule
被创建 public
checkstyle 会抱怨:
[INFO] --- maven-checkstyle-plugin:2.15:checkstyle (checkstyle-test) @ web-edge-server ---
[INFO] Starting audit...
SomeTest.java: Variable 'someRule' must be private and have accessor methods.
所以两个问题:
- 如果我想继续使用
@Rule
注释,有什么方法可以在本地或在测试中抑制此警告,而无需全局禁用 checkstyle 规则。
- 有谁知道为什么 junit 要求
@Rule
为 public?这似乎是不必要的,因为在任何情况下都可以使用反射访问它。
编辑:第 2 项具体包含在此 SO question。
在您的 checkstyle xml 中,您可以指定 suppression filter 如下:
<module name="SuppressionFilter">
<property name="file" value="${samedir}/suppressions.xml"/>
</module>
然后您可以明确地从测试中排除该检查:
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress checks="VisibilityModifier" files="[/\]src[/\]test[/\]java[/\]" />
</suppressions>
在 Checkstyle 6.5 VisibilityModifier
中检查获得的新 属性 ignoreAnnotationCanonicalNames
默认设置为 org.junit.Rule
,因此 @Rule
字段不应触发违规这张支票。
根据 release history page,Checkstyle Maven 插件 2.15 在底层使用 Checkstyle 6.1.1,因此将插件更新到 2.17 就足以进行修复。
另一个可以用来解决这个问题的选项无需升级到插件的 2.17 版本是简单地使用注释来打开和关闭检查样式:
//CHECKSTYLE:OFF
@Rule
public ExpectedException thrown = ExpectedException.none();
//CHECKSTYLE:ON
Junit @Rules and maven-checkstyle-plugin 似乎彼此不和
如果 @Rule
是 private
或包私有那么结果是:
java.lang.Exception: The @Rule 'someRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError
但是如果 @Rule
被创建 public
checkstyle 会抱怨:
[INFO] --- maven-checkstyle-plugin:2.15:checkstyle (checkstyle-test) @ web-edge-server ---
[INFO] Starting audit...
SomeTest.java: Variable 'someRule' must be private and have accessor methods.
所以两个问题:
- 如果我想继续使用
@Rule
注释,有什么方法可以在本地或在测试中抑制此警告,而无需全局禁用 checkstyle 规则。 - 有谁知道为什么 junit 要求
@Rule
为 public?这似乎是不必要的,因为在任何情况下都可以使用反射访问它。
编辑:第 2 项具体包含在此 SO question。
在您的 checkstyle xml 中,您可以指定 suppression filter 如下:
<module name="SuppressionFilter">
<property name="file" value="${samedir}/suppressions.xml"/>
</module>
然后您可以明确地从测试中排除该检查:
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress checks="VisibilityModifier" files="[/\]src[/\]test[/\]java[/\]" />
</suppressions>
在 Checkstyle 6.5 VisibilityModifier
中检查获得的新 属性 ignoreAnnotationCanonicalNames
默认设置为 org.junit.Rule
,因此 @Rule
字段不应触发违规这张支票。
根据 release history page,Checkstyle Maven 插件 2.15 在底层使用 Checkstyle 6.1.1,因此将插件更新到 2.17 就足以进行修复。
另一个可以用来解决这个问题的选项无需升级到插件的 2.17 版本是简单地使用注释来打开和关闭检查样式:
//CHECKSTYLE:OFF
@Rule
public ExpectedException thrown = ExpectedException.none();
//CHECKSTYLE:ON