Search code examples
javajunitabstract-syntax-treepmd

Ignore PMD rule for methods with a Test annotation


I use PMD for a Spring Boot project which contains MockMvc tests. The class enforces the user to catch the general Exception.

class MockMvc {
    public ResultActions perform(RequestBuilder requestBuilder) throws Exception {}
}

The usage leads to a PMD error - SignatureDeclareThrowsException. I would like to suppress the check for all @Test methods. Therefore I tried to follow a Stackoverflow answer but the configuration change has no effect.

<rule ref="rulesets/java/strictexception.xml/SignatureDeclareThrowsException" >
    <properties>
        <!-- Ignore @Test methods -->
        <property name="violationSuppressXPath" value="
        //ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation//Name[@Image='Test']" />
    </properties>
</rule>

How could I achieve it?


Abstract Syntax Tree shows the following sub tree for the test method.

> ClassOrInterfaceBodyDeclaration
  > Annotation
    > MarkerAnnotation
      > Name:Test
  > MethodDeclaration:(public)
    > ResultType:(void)
    ...

Solution

  • The specific problem with test methods can be solved in version with the IgnoreJUnitCompletely property.

    <!-- PMD > version 6.* -->
    <rule ref="category/java/design.xml/SignatureDeclareThrowsException" >
        <properties>
            <property name="IgnoreJUnitCompletely" value="true" />
        </properties>
    </rule>
    

    Before PMD 6 you have to take the rule from typeresolution.xml but not strictexception.xml.

    <!-- PMD > version 4.* -->
    <rule ref="rulesets/java/typeresolution.xml/SignatureDeclareThrowsException">
        <properties>
            <property name="IgnoreJUnitCompletely" value="true" />
        </properties>
    </rule>
    

    But it doesn't answer the question about the violationSuppressXPath problem.