View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule;
5   
6   import static org.junit.Assert.assertEquals;
7   
8   import java.io.StringReader;
9   
10  import net.sourceforge.pmd.RuleContext;
11  import net.sourceforge.pmd.lang.LanguageRegistry;
12  import net.sourceforge.pmd.lang.LanguageVersionHandler;
13  import net.sourceforge.pmd.lang.ParserOptions;
14  import net.sourceforge.pmd.lang.java.JavaLanguageModule;
15  import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
16  import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
17  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
18  import net.sourceforge.pmd.lang.java.symboltable.ScopeAndDeclarationFinder;
19  
20  import org.junit.Test;
21  
22  /**
23   * @author Philip Graf
24   */
25  public class JavaRuleViolationTest {
26      /**
27       * Verifies that {@link JavaRuleViolation} sets the variable name for an {@link ASTFormalParameter} node.
28       */
29      @Test
30      public void testASTFormalParameterVariableName() {
31          ASTCompilationUnit ast = parse("class Foo { void bar(int x) {} }");
32          final ASTFormalParameter node = ast.getFirstDescendantOfType(ASTFormalParameter.class);
33          final RuleContext context = new RuleContext();
34          final JavaRuleViolation violation = new JavaRuleViolation(null, context, node, null);
35          assertEquals("x", violation.getVariableName());
36      }
37  
38      private ASTCompilationUnit parse(final String code) {
39          final LanguageVersionHandler languageVersionHandler = LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getDefaultVersion().getLanguageVersionHandler();
40          final ParserOptions options = languageVersionHandler.getDefaultParserOptions();
41          final ASTCompilationUnit ast = (ASTCompilationUnit) languageVersionHandler.getParser(options).parse(null, new StringReader(code));
42          // set scope of AST nodes
43          ast.jjtAccept(new ScopeAndDeclarationFinder(), null);
44          return ast;
45      }
46  
47      /**
48       * Tests that the method name is taken correctly from the given node.
49       * @see <a href="https://sourceforge.net/p/pmd/bugs/1250/">#1250</a>
50       */
51      @Test
52      public void testMethodName() {
53          ASTCompilationUnit ast = parse("class Foo { void bar(int x) {} }");
54          ASTMethodDeclaration md = ast.getFirstDescendantOfType(ASTMethodDeclaration.class);
55          final RuleContext context = new RuleContext();
56          final JavaRuleViolation violation = new JavaRuleViolation(null, context, md, null);
57          assertEquals("bar", violation.getMethodName());
58      }
59  }