View Javadoc
1   package org.junit.tests.listening;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.assertNotSame;
5   
6   import org.junit.Test;
7   import org.junit.runner.Description;
8   import org.junit.runner.JUnitCore;
9   import org.junit.runner.Result;
10  import org.junit.runner.notification.Failure;
11  import org.junit.runner.notification.RunListener;
12  
13  public class TestListenerTest {
14  
15      int count;
16  
17      class ErrorListener extends RunListener {
18          @Override
19          public void testRunStarted(Description description) throws Exception {
20              throw new Error();
21          }
22      }
23  
24      public static class OneTest {
25          @Test
26          public void nothing() {
27          }
28      }
29  
30      @Test(expected = Error.class)
31      public void failingListener() {
32          JUnitCore runner = new JUnitCore();
33          runner.addListener(new ErrorListener());
34          runner.run(OneTest.class);
35      }
36  
37      class ExceptionListener extends ErrorListener {
38          @Override
39          public void testRunStarted(Description description) throws Exception {
40              count++;
41              throw new Exception();
42          }
43      }
44  
45      @Test
46      public void reportsFailureOfListener() {
47          JUnitCore core = new JUnitCore();
48          core.addListener(new ExceptionListener());
49  
50          count = 0;
51          Result result = core.run(OneTest.class);
52          assertEquals(1, count);
53          assertEquals(1, result.getFailureCount());
54          Failure testFailure = result.getFailures().get(0);
55          assertEquals(Description.TEST_MECHANISM, testFailure.getDescription());
56      }
57  
58      @Test
59      public void freshResultEachTime() {
60          JUnitCore core = new JUnitCore();
61          Result first = core.run(OneTest.class);
62          Result second = core.run(OneTest.class);
63          assertNotSame(first, second);
64      }
65  }