1 package org.mockitoutil;
2 
3 import static org.junit.Assert.assertEquals;
4 
5 /**
6  * Clean asserts for exception handling
7  */
8 public class ThrowableAssert {
9 
10     private Throwable reportedException;
11 
ThrowableAssert(Runnable runnable)12     private ThrowableAssert(Runnable runnable) {
13         try {
14             runnable.run();
15         } catch (Throwable t) {
16             this.reportedException = t;
17             return;
18         }
19         throw new AssertionError("Expected runnable to throw an exception but it didn't");
20     }
21 
throwsException(Class<? extends Throwable> exceptionType)22     public ThrowableAssert throwsException(Class<? extends Throwable> exceptionType) {
23         if(!exceptionType.isInstance(reportedException)) {
24             throw new AssertionError("Exception should be of type: "
25                     + exceptionType.getSimpleName() + " but it was: "
26                     + reportedException.getClass().getSimpleName());
27         }
28         return this;
29     }
30 
throwsMessage(String exceptionMessage)31     public ThrowableAssert throwsMessage(String exceptionMessage) {
32         assertEquals(exceptionMessage, reportedException.getMessage());
33         return this;
34     }
35 
36     /**
37      * Executes provided runnable, expects it to throw an exception.
38      * Then, it offers ways to assert on the expected exception.
39      */
assertThat(Runnable runnable)40     public static ThrowableAssert assertThat(Runnable runnable) {
41         return new ThrowableAssert(runnable);
42     }
43 }
44