I am using Checkstyle 10.5 within IntelliJ 2022.3.1. I would like to suppress magic number checks within test methods by using SuppressionXpathSingleFilter
in the configuration file. I prefer not to use a separate suppressions file because my configuration file will be shared, and I do not want to annotate the source to disable checks.
MyTest.java
class MyTest {
public int testOne() {
return 95;
}
public int TestTwo() {
return 96;
}
}
There are 3 style errors:
testOne()
TestTwo()
TestTwo()
test-checks.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="TreeWalker">
<module name="MethodName"/>
<module name="MagicNumber"/>
<module name="SuppressionXpathSingleFilter">
<property name="files" value="MyTest.java"/>
<property name="checks" value="MagicNumber"/>
<property name="query" value="//METHOD_DEF[./IDENT[@text='testOne']]"/>
</module>
</module>
</module>
When I run checkstyle, I expect to see only violations in TestTwo
:
Name 'TestTwo' must match pattern '^[a-z][a-zA-Z0-9]*$'. (6:16) [MethodName]
'96' is a magic number. (7:16) [MagicNumber]
I actually still see the magic number violation in testOne()
:
'95' is a magic number. (3:16) [MagicNumber]
Name 'TestTwo' must match pattern '^[a-z][a-zA-Z0-9]*$'. (6:16) [MethodName]
'96' is a magic number. (7:16) [MagicNumber]
I have tried different path values in test-checks.xml
, such as:
"//CLASS_DEF[@text='MyTest']/OBJBLOCK/METHOD_DEF[@text='testOne']/IDENT"
No matter what I do, the result is the same. How do I disable a specific check within a specific method without a separate suppression file or annotating the code?
The SuppressionXpathSingleFilter
documentation is confusing and it seems it contains outdated examples. If you check the XPathFilterElement
you can see the XPath expression must match the AST leaf node so the easiest way to fix the XPath query
property is to add a wildcard at the end:
<property name="query" value="//METHOD_DEF[./IDENT[@text='testOne']]//*"/>