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 net.sourceforge.pmd.lang.java.ast.ASTBlock;
8   import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
9   import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
10  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
11  import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil;
12  
13  /**
14   * Rule to check that JUnit/TestNG test methods contain at least one
15   * assertion. Unlike the PMD built-in
16   * {@code UnitTestShouldIncludeAssert} rule (PMD #4272), this
17   * implementation descends into lambda bodies, so an assertion placed
18   * inside a lambda passed to another method is still recognised.
19   * @since 0.26.0
20   */
21  public final class UnitTestShouldIncludeAssertRule
22      extends AbstractJavaRulechainRule {
23  
24      public UnitTestShouldIncludeAssertRule() {
25          super(ASTMethodDeclaration.class);
26      }
27  
28      @Override
29      public Object visit(final ASTMethodDeclaration method, final Object data) {
30          final ASTBlock body = method.getBody();
31          if (body != null
32              && TestFrameworksUtil.isTestMethod(method)
33              && !TestFrameworksUtil.isExpectAnnotated(method)
34              && body.descendants(ASTMethodCall.class)
35                  .crossFindBoundaries(true)
36                  .none(TestFrameworksUtil::isProbableAssertCall)) {
37              asCtx(data).addViolation(method);
38          }
39          return data;
40      }
41  }