View Javadoc
1   package org.junit.tests.validation;
2   
3   import static org.junit.Assert.assertEquals;
4   
5   import org.junit.Before;
6   import org.junit.Test;
7   import org.junit.internal.runners.JUnit4ClassRunner;
8   import org.junit.runner.JUnitCore;
9   import org.junit.runner.Result;
10  import org.junit.runner.RunWith;
11  import org.junit.runner.notification.Failure;
12  
13  @SuppressWarnings("deprecation")
14  public class BadlyFormedClassesTest {
15      public static class FaultyConstructor {
16          public FaultyConstructor() throws Exception {
17              throw new Exception("Thrown during construction");
18          }
19  
20          @Test
21          public void someTest() {
22              /*
23                  * Empty test just to fool JUnit and IDEs into running this class as
24                  * a JUnit test
25                  */
26          }
27      }
28  
29      ;
30  
31      @RunWith(JUnit4ClassRunner.class)
32      public static class BadBeforeMethodWithLegacyRunner {
33          @Before
34          void before() {
35  
36          }
37  
38          @Test
39          public void someTest() {
40          }
41      }
42  
43      ;
44  
45      public static class NoTests {
46          // class without tests
47      }
48  
49      @Test
50      public void constructorException() {
51          String message = exceptionMessageFrom(FaultyConstructor.class);
52          assertEquals("Thrown during construction", message);
53      }
54  
55      @Test
56      public void noRunnableMethods() {
57          assertEquals("No runnable methods", exceptionMessageFrom(NoTests.class));
58      }
59  
60      @Test
61      public void badBeforeMethodWithLegacyRunner() {
62          assertEquals("Method before should be public",
63                  exceptionMessageFrom(BadBeforeMethodWithLegacyRunner.class));
64      }
65  
66      private String exceptionMessageFrom(Class<?> testClass) {
67          JUnitCore core = new JUnitCore();
68          Result result = core.run(testClass);
69          Failure failure = result.getFailures().get(0);
70          String message = failure.getException().getMessage();
71          return message;
72      }
73  }