Custom java rule to detect missing annotation in unit test

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));
    }
  }

Hi,

What language is this for?

 
Ann

It is for Java. More precisely: a java spring boot app that uses junit4 to run unit tests.

1 Like

I’ve just found the issue. I’ve realized that I added my rule to getJavaChecks instead of getJavaTestChecks. Beginner’s mistake :smile:.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.