View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.lang.java.rule.junit;
    5
    6   import net.sourceforge.pmd.lang.java.ast.ASTArguments;
    7   import net.sourceforge.pmd.lang.java.ast.ASTName;
    8   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
    9   import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
    10
    11  import java.util.ArrayList;
    12  import java.util.List;
    13
    14  public class JUnitAssertionsShouldIncludeMessageRule extends AbstractJUnitRule {
    15
    16      private static class AssertionCall {
    17          public int args;
    18          public String name;
    19
    20          public AssertionCall(int args, String name) {
    21              this.args = args;
    22              this.name = name;
    23          }
    24      }
    25
    26      private List<AssertionCall> checks = new ArrayList<AssertionCall>();
    27
    28      public JUnitAssertionsShouldIncludeMessageRule() {
    29          checks.add(new AssertionCall(2, "assertEquals"));
    30          checks.add(new AssertionCall(1, "assertTrue"));
    31          checks.add(new AssertionCall(1, "assertNull"));
    32          checks.add(new AssertionCall(2, "assertSame"));
    33          checks.add(new AssertionCall(1, "assertNotNull"));
    34          checks.add(new AssertionCall(1, "assertFalse"));
    35      }
    36
    37      public Object visit(ASTArguments node, Object data) {
    38          for (AssertionCall call : checks) {
    39              check(data, node, call.args, call.name);
    40          }
    41          return super.visit(node, data);
    42      }
    43
    44      private void check(Object ctx, ASTArguments node, int args, String targetMethodName) {
    45          if (node.getArgumentCount() == args && node.jjtGetParent().jjtGetParent() instanceof ASTPrimaryExpression) {
    46              ASTPrimaryExpression primary = (ASTPrimaryExpression) node.jjtGetParent().jjtGetParent();
    47              if (primary.jjtGetChild(0) instanceof ASTPrimaryPrefix && primary.jjtGetChild(0).jjtGetNumChildren() > 0 && primary.jjtGetChild(0).jjtGetChild(0) instanceof ASTName) {
    48                  ASTName name = (ASTName) primary.jjtGetChild(0).jjtGetChild(0);
    49                  if (name.hasImageEqualTo(targetMethodName)) {
    50                      addViolation(ctx, name);
    51                  }
    52              }
    53          }
    54      }
    55  }