我将PMD用于包含MockMvc
测试的Spring Boot项目。该类强制用户捕获常规Exception
。
class MockMvc {
public ResultActions perform(RequestBuilder requestBuilder) throws Exception {}
}
用法会导致PMD错误-SignatureDeclareThrowsException。我想取消对所有@Test
方法的检查。因此,我尝试遵循Stackoverflow answer,但配置更改无效。
<rule ref="rulesets/java/strictexception.xml/SignatureDeclareThrowsException" >
<properties>
<!-- Ignore @Test methods -->
<property name="violationSuppressXPath" value="
//ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation//Name[@Image='Test']" />
</properties>
</rule>
我如何实现?
抽象语法树显示了测试方法的以下子树。
> ClassOrInterfaceBodyDeclaration
> Annotation
> MarkerAnnotation
> Name:Test
> MethodDeclaration:(public)
> ResultType:(void)
...
答案 0 :(得分:3)
可以使用IgnoreJUnitCompletely
属性在版本中解决测试方法的特定问题。
<!-- PMD > version 6.* -->
<rule ref="category/java/design.xml/SignatureDeclareThrowsException" >
<properties>
<property name="IgnoreJUnitCompletely" value="true" />
</properties>
</rule>
在PMD 6之前,您必须从typeresolution.xml
而不是strictexception.xml
接受规则。
<!-- PMD > version 4.* -->
<rule ref="rulesets/java/typeresolution.xml/SignatureDeclareThrowsException">
<properties>
<property name="IgnoreJUnitCompletely" value="true" />
</properties>
</rule>
但是它无法回答有关violationSuppressXPath
问题的问题。
答案 1 :(得分:1)
在PMD documentation中,JUnit4TestShouldUseTestAnnotation部分
//ClassOrInterfaceDeclaration[
matches(@Image, $testClassPattern)
or ExtendsList/ClassOrInterfaceType[pmd-java:typeIs('junit.framework.TestCase')]]
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration[MethodDeclaration[@Public=true()]/MethodDeclarator[starts-with(@Image, 'test')]]
[not(Annotation//Name[pmd-java:typeIs('org.junit.Test')])]
建议Annotation//Name[pmd-java:typeIs('org.junit.Test')]
应该足够