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