Sometimes I just want to check for an exception without
- Exiting the test case
- Adding a lot of exception handling crap in the test code.
Java 8 to the rescue!
package se.fnord; import org.junit.Test; import static org.junit.Assert.fail; public class AssertThrows { @FunctionalInterface interface ThrowingMethod { void run() throws Throwable; } private static void assertThrows(Class<? extends Throwable> expected, ThrowingMethod method) { try { method.run(); fail("Method did not throw"); } catch (Throwable t) { if (expected != t.getClass()) fail("Unexpected exception " + t.getClass()); } } @Test public void testMatchedException() { assertThrows(IllegalArgumentException.class, () -> { throw new IllegalArgumentException(); }); } @Test(expected=AssertionError.class) public void testUnmatchedException() { assertThrows(IllegalArgumentException.class, () -> { throw new IllegalStateException(); }); } }