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.Rule; 8 import net.sourceforge.pmd.rules.design.SwitchDensityRule; 9 import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst; 10 import test.net.sourceforge.pmd.testframework.TestDescriptor; 11 12 public class SwitchDensityTest extends SimpleAggregatorTst { 13 14 private Rule rule; 15 16 public void setUp() { 17 rule = new SwitchDensityRule(); 18 rule.addProperty("minimum", "4"); 19 } 20 21 public void testAll() { 22 runTests(new TestDescriptor[]{ 23 new TestDescriptor(TEST1, "Five stmts in one switch case, should be flagged", 1, rule), 24 new TestDescriptor(TEST2, "One stmt in one switch case, ok", 0, rule), 25 new TestDescriptor(TEST3, "Five stmts, 5 cases, OK", 0, rule), 26 }); 27 } 28 29 private static final String TEST1 = 30 "// Switch Density = 5.0" + PMD.EOL + 31 "public class SwitchDensity1 {" + PMD.EOL + 32 " public void foo(int i) {" + PMD.EOL + 33 " switch (i) {" + PMD.EOL + 34 " case 0:" + PMD.EOL + 35 " {" + PMD.EOL + pad(5) + 36 " }" + PMD.EOL + 37 " }" + PMD.EOL + 38 " }" + PMD.EOL + 39 "}"; 40 41 private static final String TEST2 = 42 "// Switch Density = 1.0" + PMD.EOL + 43 "public class SwitchDensity2 {" + PMD.EOL + 44 " public void foo(int i) {" + PMD.EOL + 45 " switch (i) {" + PMD.EOL + 46 " case 0:" + PMD.EOL + 47 " {" + PMD.EOL + pad(1) + 48 " }" + PMD.EOL + 49 " }" + PMD.EOL + 50 " }" + PMD.EOL + 51 "}"; 52 53 private static final String TEST3 = 54 "// Switch Density = 1.0" + PMD.EOL + 55 "public class SwitchDensity3 {" + PMD.EOL + 56 " public void foo(int i) {" + PMD.EOL + 57 " switch (i) {" + PMD.EOL + 58 " case 0:" + PMD.EOL + 59 " case 1:" + PMD.EOL + 60 " case 2:" + PMD.EOL + 61 " case 3:" + PMD.EOL + 62 " case 4:" + PMD.EOL + 63 " {" + PMD.EOL + pad(5) + 64 " }" + PMD.EOL + 65 " } " + PMD.EOL + 66 " }" + PMD.EOL + 67 "}"; 68 69 private static String pad(int times) { 70 String x = ""; 71 for (int i = 0; i < times; i++) { 72 x += "System.err.println(\"I am a fish.\");" + PMD.EOL; 73 } 74 return x; 75 } 76 77 }