Junit @Rules和maven-checkstyle-plugin似乎相互矛盾。
如果@Rule
为private
或包私有,则结果为:
java.lang.Exception: The @Rule 'someRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError
但如果@Rule
成为public
,则检查风格会抱怨:
[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规则。@Rule
公开?这似乎是不必要的,因为在任何情况下都可以使用反射来访问它。编辑:此SO question具体涵盖了第2项。
答案 0 :(得分:3)
在Checkstyle 6.5中VisibilityModifier
检查获得新属性ignoreAnnotationCanonicalNames
,默认情况下设置为org.junit.Rule
,因此@Rule
字段不应触发此检查中的违规行为。
根据release history page,Checkstyle Maven Plugin 2.15使用了下面的Checkstyle 6.1.1,因此将插件更新为2.17 就足以进行修复。
答案 1 :(得分:2)
在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>
答案 2 :(得分:0)
可用于解决此问题而升级到插件版本2.17的另一个选项是简单地使用注释来打开和关闭检查样式:
//CHECKSTYLE:OFF
@Rule
public ExpectedException thrown = ExpectedException.none();
//CHECKSTYLE:ON