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.Rule;
8 import net.sourceforge.pmd.RuleContext;
9 import net.sourceforge.pmd.ast.ASTArguments;
10 import net.sourceforge.pmd.ast.ASTName;
11 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
12 import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
13
14 import java.util.ArrayList;
15 import java.util.Iterator;
16 import java.util.List;
17
18 public class JUnitAssertionsShouldIncludeMessageRule extends AbstractRule implements Rule {
19
20 private static class AssertionCall {
21 public int args;
22 public String name;
23
24 public AssertionCall(int args, String name) {
25 this.args = args;
26 this.name = name;
27 }
28 }
29
30 private List checks = new ArrayList();
31
32 public JUnitAssertionsShouldIncludeMessageRule() {
33 checks.add(new AssertionCall(2, "assertEquals"));
34 checks.add(new AssertionCall(1, "assertTrue"));
35 checks.add(new AssertionCall(1, "assertNull"));
36 checks.add(new AssertionCall(2, "assertSame"));
37 checks.add(new AssertionCall(1, "assertNotNull"));
38 }
39
40 public Object visit(ASTArguments node, Object data) {
41 for (Iterator i = checks.iterator(); i.hasNext();) {
42 AssertionCall call = (AssertionCall) i.next();
43 check((RuleContext) data, node, call.args, call.name);
44 }
45 return super.visit(node, data);
46 }
47
48 private void check(RuleContext ctx, ASTArguments node, int args, String targetMethodName) {
49 if (node.getArgumentCount() == args && node.jjtGetParent().jjtGetParent() instanceof ASTPrimaryExpression) {
50 ASTPrimaryExpression primary = (ASTPrimaryExpression) node.jjtGetParent().jjtGetParent();
51 if (primary.jjtGetChild(0) instanceof ASTPrimaryPrefix && primary.jjtGetChild(0).jjtGetNumChildren() > 0 && primary.jjtGetChild(0).jjtGetChild(0) instanceof ASTName) {
52 ASTName name = (ASTName) primary.jjtGetChild(0).jjtGetChild(0);
53 if (name.getImage().equals(targetMethodName)) {
54 ctx.getReport().addRuleViolation(createRuleViolation(ctx, name.getBeginLine()));
55 }
56 }
57 }
58 }
59 }
This page was automatically generated by Maven