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