Hello,
I’m having issues with my custom rule as described below. Any thoughts?
sonarqube version: Version 8.9.9 (build 56886)
what I’m trying to achieve
Create a custom rule that detects when a test method is missing DisplayName annotation
This is what I’ve done so far
I have created a custom rule to detect when DisplayName annotation is missing for a test method. I’ve created a unit test to test my rule in “java-custom-rule-example” and it pass. Added the rule to sonarqube and have it activated. However, after running the analysis, the issue is not detected.
Code
I have created a rule class that extends from IssuableSubscriptionVisitor and implemented visitNode method as follows:
private static final String DEFAULT_VALUE = "DisplayName";
@Override
public void visitNode(Tree tree) {
MethodTree method = (MethodTree) tree;
if (!isJunit4TestMethod(method)) {
// any other method which is not a test
return;
}
boolean annotationExists = false;
List<AnnotationTree> annotations = method.modifiers().annotations();
IdentifierTree identifier = null;
for (AnnotationTree annotationTree : annotations) {
TypeTree annotationType = annotationTree.annotationType();
if (annotationType.is(Tree.Kind.IDENTIFIER)) {
identifier = (IdentifierTree) annotationType;
if (identifier.name().equals(DEFAULT_VALUE)) {
annotationExists = true;
break;
}
}
}
if(!annotationExists) {
reportIssue(method.simpleName(), String.format("Missing annotation @%s", DEFAULT_VALUE));
}
}