KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > junit > JUnitAssertionsShouldIncludeMessage


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 JavaDoc;
13 import java.util.Iterator JavaDoc;
14 import java.util.List JavaDoc;
15
16 public class JUnitAssertionsShouldIncludeMessage extends AbstractRule {
17
18     private static class AssertionCall {
19         public int args;
20         public String JavaDoc name;
21
22         public AssertionCall(int args, String JavaDoc name) {
23             this.args = args;
24             this.name = name;
25         }
26     }
27
28     private List JavaDoc checks = new ArrayList JavaDoc();
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 JavaDoc visit(ASTArguments node, Object JavaDoc data) {
40         for (Iterator JavaDoc 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 JavaDoc ctx, ASTArguments node, int args, String JavaDoc 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 }
59
Popular Tags