View Javadoc

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