1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package test.net.sourceforge.pmd.rules.strings;
5   
6   import net.sourceforge.pmd.PMD;
7   import net.sourceforge.pmd.Rule;
8   import net.sourceforge.pmd.RuleSetNotFoundException;
9   import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst;
10  import test.net.sourceforge.pmd.testframework.TestDescriptor;
11  
12  public class StringInstantiationRuleTest extends SimpleAggregatorTst {
13  
14      private Rule rule;
15  
16      public void setUp() throws RuleSetNotFoundException {
17          rule = findRule("strings", "StringInstantiation");
18      }
19  
20      public void testAll() {
21          runTests(new TestDescriptor[]{
22              new TestDescriptor(TEST1, "new 'new String's", 2, rule),
23              new TestDescriptor(TEST2, "new String array", 0, rule),
24              new TestDescriptor(TEST3, "using multiple parameter constructor", 0, rule),
25              new TestDescriptor(TEST4, "using 4 parameter constructor", 0, rule),
26              new TestDescriptor(TEST5, "byte array constructor is ok", 0, rule)
27          });
28      }
29  
30      private static final String TEST1 =
31              "public class Foo {" + PMD.EOL +
32              " private String bar = new String(\"bar\");" + PMD.EOL +
33              " private String baz = new String();" + PMD.EOL +
34              "}";
35  
36      private static final String TEST2 =
37              "public class Foo {" + PMD.EOL +
38              " private String[] bar = new String[5];" + PMD.EOL +
39              "}";
40  
41      private static final String TEST3 =
42              "public class Foo {" + PMD.EOL +
43              " void foo() {" + PMD.EOL +
44              "  byte[] bytes = new byte[50];" + PMD.EOL +
45              "  String bar = new String(bytes, 0, bytes.length);" + PMD.EOL +
46              " }" + PMD.EOL +
47              "}";
48  
49      private static final String TEST4 =
50              "public class Foo {" + PMD.EOL +
51              " void foo() {" + PMD.EOL +
52              "  byte[] bytes = new byte[50];" + PMD.EOL +
53              "  String bar = new String(bytes, 0, bytes.length, \"some-encoding\");" + PMD.EOL +
54              " }" + PMD.EOL +
55              "}";
56  
57      private static final String TEST5 =
58              "public class Foo {" + PMD.EOL +
59              " void foo() {" + PMD.EOL +
60              "  byte[] bytes = new byte[50];" + PMD.EOL +
61              "  String bar = new String(bytes);" + PMD.EOL +
62              " }" + PMD.EOL +
63              "}";
64  
65  
66  }