    1   /***
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package test.net.sourceforge.pmd.rules;
    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 AssignmentInOperandTest extends SimpleAggregatorTst {
    13
    14      private Rule rule;
    15
    16      public void setUp() throws RuleSetNotFoundException {
    17          rule = findRule("controversial", "AssignmentInOperand");
    18      }
    19
    20      public void testAll() {
    21          runTests(new TestDescriptor[]{
    22              new TestDescriptor(TEST1, "bad", 1, rule),
    23              new TestDescriptor(TEST2, "ok", 0, rule),
    24              new TestDescriptor(TEST3, "assignment in if conditional expression", 0, rule),
    25              new TestDescriptor(TEST4, "assignment in while conditional expression", 1, rule),
    26          });
    27      }
    28
    29      private static final String TEST1 =
    30              "public class Foo {" + PMD.EOL +
    31              " public void bar() {" + PMD.EOL +
    32              "  int x = 2;" + PMD.EOL +
    33              "  if ((x = getX()) == 3) {" + PMD.EOL +
    34              "   System.out.println(\"3!\");" + PMD.EOL +
    35              "  }" + PMD.EOL +
    36              " }" + PMD.EOL +
    37              " private int getX() {" + PMD.EOL +
    38              "  return 3;" + PMD.EOL +
    39              " }" + PMD.EOL +
    40              "}";
    41
    42      private static final String TEST2 =
    43              "public class Foo {" + PMD.EOL +
    44              " public void bar() {" + PMD.EOL +
    45              "  if (false) {}" + PMD.EOL +
    46              " }" + PMD.EOL +
    47              "}";
    48
    49      private static final String TEST3 =
    50              "public class Foo {" + PMD.EOL +
    51              " public void bar() {" + PMD.EOL +
    52              "  if (false) {" + PMD.EOL +
    53              "   int x =2;" + PMD.EOL +
    54              "  }" + PMD.EOL +
    55              " }" + PMD.EOL +
    56              "}";
    57
    58      private static final String TEST4 =
    59              "public class Foo {" + PMD.EOL +
    60              " public void bar() {" + PMD.EOL +
    61              "  int x = 2;" + PMD.EOL +
    62              "  while ( (x = getX()) != 0 ) {}" + PMD.EOL +
    63              " }" + PMD.EOL +
    64              " private int getX() {return 2;}" + PMD.EOL +
    65              "}";
    66  }