1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package test.net.sourceforge.pmd.rules.design;
5   
6   import net.sourceforge.pmd.PMD;
7   import net.sourceforge.pmd.rules.design.PositionalIteratorRule;
8   import test.net.sourceforge.pmd.testframework.RuleTst;
9   
10  public class PositionalIteratorRuleTest extends RuleTst {
11  
12      private static final String TEST1 =
13              "public class PositionalIterator1 {" + PMD.EOL +
14              " public void foo(Iterator i) {" + PMD.EOL +
15              "  while(i.hasNext()) {" + PMD.EOL +
16              "   Object one = i.next();" + PMD.EOL +
17              "   " + PMD.EOL +
18              "   // 2 calls to next() inside the loop == bad!" + PMD.EOL +
19              "   Object two = i.next(); " + PMD.EOL +
20              "  }" + PMD.EOL +
21              " }" + PMD.EOL +
22              "}";
23  
24      private static final String TEST2 =
25              "public class PositionalIterator2 {" + PMD.EOL +
26              " public void foo(Iterator i) {" + PMD.EOL +
27              "  while(i.hasNext()) {" + PMD.EOL +
28              "   Object one = i.next();" + PMD.EOL +
29              "  }" + PMD.EOL +
30              " }" + PMD.EOL +
31              "}";
32  
33      private static final String TEST3 =
34              "public class PositionalIterator3 {" + PMD.EOL +
35              " public void foo() {" + PMD.EOL +
36              "  Iterator i = (new List()).iterator();" + PMD.EOL +
37              "  while(i.hasNext()) {" + PMD.EOL +
38              "   Object one = i.next();" + PMD.EOL +
39              "   Iterator j = (new List()).iterator();" + PMD.EOL +
40              "   while (j.hasNext()) {" + PMD.EOL +
41              "    j.next();" + PMD.EOL +
42              "   }" + PMD.EOL +
43              "  }" + PMD.EOL +
44              " }" + PMD.EOL +
45              "}";
46  
47      public void test1() throws Throwable {
48          runTestFromString(TEST1, 1, new PositionalIteratorRule());
49      }
50  
51      public void test2() throws Throwable {
52          runTestFromString(TEST2, 0, new PositionalIteratorRule());
53      }
54  
55      public void test3() throws Throwable {
56          runTestFromString(TEST3, 0, new PositionalIteratorRule());
57      }
58  }