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.comments;
5   
6   import static org.junit.Assert.assertEquals;
7   
8   import java.io.Reader;
9   import java.io.StringReader;
10  import java.util.List;
11  
12  import net.sourceforge.pmd.lang.LanguageVersion;
13  import net.sourceforge.pmd.lang.LanguageVersionHandler;
14  import net.sourceforge.pmd.lang.ast.Node;
15  import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
16  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
17  import net.sourceforge.pmd.lang.java.ast.FormalComment;
18  import net.sourceforge.pmd.lang.java.ast.MultiLineComment;
19  import net.sourceforge.pmd.lang.java.ast.Token;
20  
21  import org.junit.Assert;
22  import org.junit.Test;
23  
24  public class AbstractCommentRuleTest {
25  
26  	private AbstractCommentRule testSubject = new AbstractCommentRule() {};
27  
28  	/**
29  	 * Blank lines in comments should not raise an exception.
30  	 * See bug #1048.
31  	 */
32  	@Test
33  	public void testFilteredCommentIn() {
34  		Token token = new Token();
35  		token.image = "/* multi line comment with blank lines\n\n\n */";
36  
37  		String filtered = testSubject.filteredCommentIn(new MultiLineComment(token));
38  		assertEquals("multi line comment with blank lines", filtered);
39  
40  		token.image = "/** a formal comment with blank lines\n\n\n */";
41  		filtered = testSubject.filteredCommentIn(new FormalComment(token));
42  		assertEquals("a formal comment with blank lines", filtered);
43  	}
44  
45      @Test
46      public void testCommentAssignments() {
47          LanguageVersionHandler handler = LanguageVersion.JAVA_18.getLanguageVersionHandler();
48          Reader source = new StringReader("public class Foo {"
49                  + "     /** Comment 1 */\n" + 
50                  "        public void method1() {}\n" + 
51                  "    \n" + 
52                  "        /** Comment 2 */\n" + 
53                  "    \n" + 
54                  "        /** Comment 3 */\n" + 
55                  "        public void method2() {}"
56                  + "}");
57          Node node = handler.getParser(handler.getDefaultParserOptions()).parse("test", source);
58  
59          testSubject.assignCommentsToDeclarations((ASTCompilationUnit)node);
60          List<ASTMethodDeclaration> methods = node.findDescendantsOfType(ASTMethodDeclaration.class);
61          Assert.assertEquals("/** Comment 1 */", methods.get(0).comment().getImage());
62          Assert.assertEquals("/** Comment 3 */", methods.get(1).comment().getImage());
63      }
64  }