View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.pmd.rules;
6   
7   import java.util.Arrays;
8   import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
9   import net.sourceforge.pmd.lang.java.ast.ASTExpression;
10  import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
11  import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
12  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
13  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
14  
15  /**
16   * Rule to check plain assertions in JUnit tests.
17   * @since 0.17
18   */
19  public final class ProhibitPlainJunitAssertionsRule
20      extends AbstractJavaRulechainRule {
21  
22      /**
23       * Mask of prohibited imports.
24       */
25      private static final String[] PROHIBITED = {
26          "org.junit.Assert.assert",
27          "junit.framework.Assert.assert",
28      };
29  
30      /**
31       * Default constructor.
32       */
33      public ProhibitPlainJunitAssertionsRule() {
34          super(
35              ASTMethodDeclaration.class,
36              ASTImportDeclaration.class
37          );
38      }
39  
40      @Override
41      public Object visit(final ASTImportDeclaration imp, final Object data) {
42          if (Arrays.stream(ProhibitPlainJunitAssertionsRule.PROHIBITED)
43              .anyMatch(imp.getImportedName()::contains)
44          ) {
45              asCtx(data).addViolation(imp);
46          }
47          return data;
48      }
49  
50      @Override
51      public Object visit(final ASTMethodDeclaration method, final Object data) {
52          if (ProhibitPlainJunitAssertionsRule.isJUnitTest(method)) {
53              method.descendants(ASTMethodCall.class)
54                  .filter(ProhibitPlainJunitAssertionsRule::isPlainJunitAssert)
55                  .toStream()
56                  .findAny()
57                  .ifPresent(call -> asCtx(data).addViolation(method));
58          }
59          return data;
60      }
61  
62      private static boolean isJUnitTest(final ASTMethodDeclaration method) {
63          return method.getDeclaredAnnotations()
64              .toStream()
65              .map(ASTAnnotation::getSimpleName).anyMatch(
66                  name -> "Test".equals(name)
67                      || "org.junit.Test".equals(name)
68                      || "org.junit.jupiter.api.Test".equals(name)
69              );
70      }
71  
72      private static boolean isPlainJunitAssert(final ASTMethodCall call) {
73          final ASTExpression qualifier = call.getQualifier();
74          return call.getMethodName().startsWith("assert") && qualifier != null
75              && "Assert".contentEquals(qualifier.getText());
76      }
77  }