有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有测试注释的方法的java Ignore PMD规则

我将PMD用于包含^{}测试的Spring引导项目。该类强制用户捕获一般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) 个答案

  1. # 1 楼答案

    测试方法的具体问题可以在具有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问题的问题

  2. # 2 楼答案

    PMD documentation开始,JUnit4Test应该使用TestAnnotation部分

    //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')]就足够了