忽略带有测试注释的方法的PMD规则

时间:2018-06-28 13:02:24

标签: java junit abstract-syntax-tree pmd

我将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)
    ...

2 个答案:

答案 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')]应该足够