All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.java.checks.tests.JUnitCompatibleAnnotationsCheck Maven / Gradle / Ivy

/*
 * SonarQube Java
 * Copyright (C) 2012-2024 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the Sonar Source-Available License for more details.
 *
 * You should have received a copy of the Sonar Source-Available License
 * along with this program; if not, see https://sonarsource.com/license/ssal/
 */
package org.sonar.java.checks.tests;

import org.sonar.check.Rule;
import org.sonarsource.analyzer.commons.collections.SetUtils;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.AnnotationTree;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.Tree;

import java.util.Collections;
import java.util.List;
import java.util.Set;

@Rule(key = "S5967")
public class JUnitCompatibleAnnotationsCheck extends IssuableSubscriptionVisitor {

  private static final Set ANNOTATIONS = SetUtils.immutableSetOf(
    "org.junit.jupiter.api.Test",
    "org.junit.jupiter.api.RepeatedTest",
    "org.junit.jupiter.api.TestFactory",
    "org.junit.jupiter.api.TestTemplate",
    "org.junit.jupiter.params.ParameterizedTest");

  @Override
  public List nodesToVisit() {
    return Collections.singletonList(Tree.Kind.METHOD);
  }

  @Override
  public void visitNode(Tree tree) {
    MethodTree method = (MethodTree) tree;
    List annotationTrees = method.modifiers().annotations();

    List locations = annotationTrees.stream()
      .filter(annotation -> ANNOTATIONS.contains(annotation.annotationType().symbolType().fullyQualifiedName()))
      .map(annotationTree -> new JavaFileScannerContext.Location("Incompatible annotation", annotationTree))
      .toList();

    if (locations.size() > 1) {
      reportIssue(method.simpleName(), "Remove one of these conflicting annotations.", locations, null);
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy