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.ast.ASTClassOrInterfaceDeclaration;
7 import net.sourceforge.pmd.ast.ASTMethodDeclaration;
8 import net.sourceforge.pmd.ast.ASTName;
9 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
10 import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
11 import net.sourceforge.pmd.ast.ASTStatementExpression;
12 import net.sourceforge.pmd.ast.Node;
13
14 public class JUnitTestsShouldContainAsserts extends AbstractJUnitRule {
15
16 public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
17 if (node.isInterface()) {
18 return data;
19 }
20 return super.visit(node, data);
21 }
22
23 public Object visit(ASTMethodDeclaration method, Object data) {
24 if (isJUnitMethod(method, data)) {
25 if (!containsAssert(method.getBlock(), false)) {
26 addViolation(data, method);
27 }
28 }
29 return data;
30 }
31
32 private boolean containsAssert(Node n, boolean assertFound) {
33 if (!assertFound) {
34 if (n instanceof ASTStatementExpression) {
35 if (isAssertOrFailStatement((ASTStatementExpression)n)) {
36 return true;
37 }
38 }
39 if (!assertFound) {
40 for (int i=0;i<n.jjtGetNumChildren() && ! assertFound;i++) {
41 Node c = n.jjtGetChild(i);
42 if (containsAssert(c, assertFound))
43 return true;
44 }
45 }
46 }
47 return false;
48 }
49
50 /**
51 * Tells if the expression is an assert statement or not.
52 */
53 private boolean isAssertOrFailStatement(ASTStatementExpression expression) {
54 if (expression!=null
55 && expression.jjtGetNumChildren()>0
56 && expression.jjtGetChild(0) instanceof ASTPrimaryExpression
57 ) {
58 ASTPrimaryExpression pe = (ASTPrimaryExpression) expression.jjtGetChild(0);
59 if (pe.jjtGetNumChildren()> 0 && pe.jjtGetChild(0) instanceof ASTPrimaryPrefix) {
60 ASTPrimaryPrefix pp = (ASTPrimaryPrefix) pe.jjtGetChild(0);
61 if (pp.jjtGetNumChildren()>0 && pp.jjtGetChild(0) instanceof ASTName) {
62 String img = ((ASTName) pp.jjtGetChild(0)).getImage();
63 if (img != null && (img.startsWith("assert") || img.startsWith("fail") || img.startsWith("Assert.assert") || img.startsWith("Assert.fail") )) {
64 return true;
65 }
66 }
67 }
68 }
69 return false;
70 }
71 }