1   package test.net.sourceforge.pmd.rules.logging.jakartacommons;
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 UseCorrectExceptionLoggingTest extends SimpleAggregatorTst {
10  
11      private Rule rule;
12  
13      public void setUp() throws RuleSetNotFoundException {
14          rule = findRule("rulesets/logging-jakarta-commons.xml", "UseCorrectExceptionLogging");
15      }
16  
17      public void testAll() {
18          runTests(new TestDescriptor[]{
19              new TestDescriptor(TEST1, "ok", 0, rule),
20              new TestDescriptor(TEST2, "failure case - two calls", 2, rule),
21              new TestDescriptor(TEST3, "must be in a catch block", 0, rule),
22          });
23      }
24  
25      private static final String TEST1 =
26              "public class Foo {" + PMD.EOL +
27              " static final Log _LOG = LogFactory.getLog( Main.class );" + PMD.EOL +
28              " void foo() {" + PMD.EOL +
29              "  try {} catch (OtherException oe) {" + PMD.EOL +
30              "   _LOG.error(oe.getMessage(), oe);" + PMD.EOL +
31              "  }" + PMD.EOL +
32              " }" + PMD.EOL +
33              "}";
34  
35      private static final String TEST2 =
36              "public class Foo {" + PMD.EOL +
37              " static final Log _LOG = LogFactory.getLog( Main.class );" + PMD.EOL +
38              " void foo() {" + PMD.EOL +
39              "  try {} catch (Exception e) {" + PMD.EOL +
40              "   _LOG.error(e);" + PMD.EOL +
41              "   _LOG.info(e);" + PMD.EOL +
42              "  } " + PMD.EOL +
43              " }" + PMD.EOL +
44              "}";
45  
46      private static final String TEST3 =
47              "public class Foo {" + PMD.EOL +
48              " static final Log _LOG = LogFactory.getLog( Main.class );" + PMD.EOL +
49              " void foo(int e) {" + PMD.EOL +
50              "  _LOG.error(e);" + PMD.EOL +
51              " }" + PMD.EOL +
52              "}";
53  }