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.symboltable.ScopeAndDeclarationFinder;
17  
18  import org.junit.Test;
19  
20  /**
21   * @author Philip Graf
22   */
23  public class JavaRuleViolationTest {
24      
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  }