Home | History | Annotate | Download | only in mockitoutil
      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 
     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 
     26     public ThrowableAssert throwsException(Class<? extends Throwable> exceptionType) {
     27         if(!exceptionType.isInstance(reportedException)) {
     28             throw new AssertionError("Exception should be of type: "
     29                     + exceptionType.getSimpleName() + " but it was: "
     30                     + reportedException.getClass().getSimpleName());
     31         }
     32         return this;
     33     }
     34 
     35     public ThrowableAssert throwsMessage(String exceptionMessage) {
     36         assertEquals(exceptionMessage, reportedException.getMessage());
     37         return this;
     38     }
     39 
     40     /**
     41      * Executes provided runnable, expects it to throw an exception.
     42      * Then, it offers ways to assert on the expected exception.
     43      */
     44     public static ThrowableAssert assertThat(Runnable runnable) {
     45         return new ThrowableAssert(runnable);
     46     }
     47 }
     48