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.ASTClassOrInterfaceDeclaration;
8   import net.sourceforge.pmd.ast.ASTMethodDeclarator;
9   
10  import java.util.Iterator;
11  import java.util.List;
12  
13  public class TestClassWithoutTestCases extends AbstractRule {
14  
15      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
16          if (node.isAbstract() || node.isInterface() || node.isNested()) {
17              return data;
18          }
19  
20          String className = node.getImage();
21          if (className.endsWith("Test")) {
22              List m = node.findChildrenOfType(ASTMethodDeclarator.class);
23              boolean testsFound = false;
24              if (m != null) {
25                  for (Iterator it = m.iterator(); it.hasNext() && !testsFound;) {
26                      ASTMethodDeclarator md = (ASTMethodDeclarator) it.next();
27                      if (!isInInnerClassOrInterface(md)
28                              && md.getImage().startsWith("test")) {
29                          testsFound = true;
30                      }
31                  }
32              }
33  
34              if (!testsFound) {
35                  addViolation(data, node);
36              }
37  
38          }
39          return data;
40      }
41  
42      private boolean isInInnerClassOrInterface(ASTMethodDeclarator md) {
43          ASTClassOrInterfaceDeclaration p = (ASTClassOrInterfaceDeclaration) md.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
44          return p != null && p.isNested();
45      }
46  }