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