    1   package test.net.sourceforge.pmd.rules.design;
    2
    3   import net.sourceforge.pmd.PMD;
    4   import net.sourceforge.pmd.Rule;
    5   import net.sourceforge.pmd.RuleSetNotFoundException;
    6   import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst;
    7   import test.net.sourceforge.pmd.testframework.TestDescriptor;
    8
    9   public class NonThreadSafeSingletonTest extends SimpleAggregatorTst {
    10
    11      private Rule rule;
    12
    13      public void setUp() throws RuleSetNotFoundException {
    14          rule = findRule("design", "NonThreadSafeSingleton");
    15      }
    16
    17      public void testAll() {
    18          runTests(new TestDescriptor[]{
    19              new TestDescriptor(TEST1, "failure case", 1, rule),
    20              new TestDescriptor(TEST2, "OK, method is synchronized", 0, rule),
    21              new TestDescriptor(TEST3, "OK, in synchronized block", 0, rule),
    22          });
    23      }
    24
    25      private static final String TEST1 =
    26              "public class Foo {" + PMD.EOL +
    27              " private static List buz;" + PMD.EOL +
    28              " public static List bar() {" + PMD.EOL +
    29              "  if (buz == null) buz = new ArrayList();" + PMD.EOL +
    30              "  return buz;" + PMD.EOL +
    31              " }" + PMD.EOL +
    32              "}";
    33
    34      private static final String TEST2 =
    35              "public class Foo {" + PMD.EOL +
    36              " private static List buz;" + PMD.EOL +
    37              " public static synchronized List bar() {" + PMD.EOL +
    38              "  if (buz == null) buz = new ArrayList();" + PMD.EOL +
    39              "  return buz;" + PMD.EOL +
    40              " }" + PMD.EOL +
    41              "}";
    42
    43      private static final String TEST3 =
    44              "public class Foo {" + PMD.EOL +
    45              " private static List buz;" + PMD.EOL +
    46              " public static List bar() {" + PMD.EOL +
    47              "  synchronized (baz) {" + PMD.EOL +
    48              "   if (buz == null) buz = new ArrayList();" + PMD.EOL +
    49              "   return buz;" + PMD.EOL +
    50              "  }" + PMD.EOL +
    51              " }" + PMD.EOL +
    52              "}";
    53
    54  }