View Javadoc
1   package org.junit.tests.running.methods;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.assertFalse;
5   import static org.junit.Assert.assertTrue;
6   
7   import org.junit.Test;
8   import org.junit.runner.JUnitCore;
9   import org.junit.runner.Result;
10  import org.junit.runner.notification.Failure;
11  
12  public class ExpectedTest {
13  
14      public static class Expected {
15          @Test(expected = Exception.class)
16          public void expected() throws Exception {
17              throw new Exception();
18          }
19      }
20  
21      @Test
22      public void expected() {
23          JUnitCore core = new JUnitCore();
24          Result result = core.run(Expected.class);
25          assertTrue(result.wasSuccessful());
26      }
27  
28      public static class Unexpected {
29          @Test(expected = Exception.class)
30          public void expected() throws Exception {
31              throw new Error();
32          }
33      }
34  
35      @Test
36      public void unexpected() {
37          Result result = JUnitCore.runClasses(Unexpected.class);
38          Failure failure = result.getFailures().get(0);
39          String message = failure.getMessage();
40          assertTrue(message.contains("expected<java.lang.Exception> but was<java.lang.Error>"));
41          assertEquals(Error.class, failure.getException().getCause().getClass());
42      }
43  
44      public static class NoneThrown {
45          @Test(expected = Exception.class)
46          public void nothing() {
47          }
48      }
49  
50      @Test
51      public void noneThrown() {
52          JUnitCore core = new JUnitCore();
53          Result result = core.run(NoneThrown.class);
54          assertFalse(result.wasSuccessful());
55          String message = result.getFailures().get(0).getMessage();
56          assertTrue(message.contains("Expected exception: java.lang.Exception"));
57      }
58  
59      public static class ExpectSuperclass {
60          @Test(expected = RuntimeException.class)
61          public void throwsSubclass() {
62              throw new ClassCastException();
63          }
64      }
65  
66      @Test
67      public void expectsSuperclass() {
68          assertTrue(new JUnitCore().run(ExpectSuperclass.class).wasSuccessful());
69      }
70  }