01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules.junit;
04:
05: import net.sourceforge.pmd.ast.ASTArguments;
06: import net.sourceforge.pmd.ast.ASTName;
07: import net.sourceforge.pmd.ast.ASTPrimaryExpression;
08: import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
09:
10: import java.util.ArrayList;
11: import java.util.List;
12:
13: public class JUnitAssertionsShouldIncludeMessage extends
14: 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 JUnitAssertionsShouldIncludeMessage() {
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,
45: String targetMethodName) {
46: if (node.getArgumentCount() == args
47: && node.jjtGetParent().jjtGetParent() instanceof ASTPrimaryExpression) {
48: ASTPrimaryExpression primary = (ASTPrimaryExpression) node
49: .jjtGetParent().jjtGetParent();
50: if (primary.jjtGetChild(0) instanceof ASTPrimaryPrefix
51: && primary.jjtGetChild(0).jjtGetNumChildren() > 0
52: && primary.jjtGetChild(0).jjtGetChild(0) instanceof ASTName) {
53: ASTName name = (ASTName) primary.jjtGetChild(0)
54: .jjtGetChild(0);
55: if (name.hasImageEqualTo(targetMethodName)) {
56: addViolation(ctx, name);
57: }
58: }
59: }
60: }
61: }
|