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   *
18   * @since 0.17
19   */
20  public final class ProhibitPlainJunitAssertionsRule
21      extends AbstractJavaRulechainRule {
22  
23      /**
24       * Mask of prohibited imports.
25       */
26      private static final String[] PROHIBITED = {
27          "org.junit.Assert.assert",
28          "junit.framework.Assert.assert",
29      };
30  
31      /**
32       * Default constructor.
33       */
34      public ProhibitPlainJunitAssertionsRule() {
35          super(
36              ASTMethodDeclaration.class,
37              ASTImportDeclaration.class
38          );
39      }
40  
41      @Override
42      public Object visit(final ASTImportDeclaration imp, final Object data) {
43          if (Arrays.stream(ProhibitPlainJunitAssertionsRule.PROHIBITED)
44              .anyMatch(imp.getImportedName()::contains)
45          ) {
46              asCtx(data).addViolation(imp);
47          }
48          return data;
49      }
50  
51      @Override
52      public Object visit(final ASTMethodDeclaration method, final Object data) {
53          if (ProhibitPlainJunitAssertionsRule.isJUnitTest(method)) {
54              method.descendants(ASTMethodCall.class)
55                  .filter(ProhibitPlainJunitAssertionsRule::isPlainJunitAssert)
56                  .toStream()
57                  .findAny()
58                  .ifPresent(call -> asCtx(data).addViolation(method));
59          }
60          return data;
61      }
62  
63      private static boolean isJUnitTest(final ASTMethodDeclaration method) {
64          return method.getDeclaredAnnotations()
65              .toStream()
66              .map(ASTAnnotation::getSimpleName).anyMatch(
67                  name -> "Test".equals(name)
68                      || "org.junit.Test".equals(name)
69                      || "org.junit.jupiter.api.Test".equals(name)
70              );
71      }
72  
73      private static boolean isPlainJunitAssert(final ASTMethodCall call) {
74          final ASTExpression qualifier = call.getQualifier();
75          return call.getMethodName().startsWith("assert") && qualifier != null
76              && "Assert".contentEquals(qualifier.getText());
77      }
78  }