How can I use JUnit4 idiomatically to test that some code throws an exception?
While I can certainly do something like this:
@Test
public void testFo
With Java 8 you can create a method taking a code to check and expected exception as parameters:
private void expectException(Runnable r, Class> clazz) {
try {
r.run();
fail("Expected: " + clazz.getSimpleName() + " but not thrown");
} catch (Exception e) {
if (!clazz.isInstance(e)) fail("Expected: " + clazz.getSimpleName() + " but " + e.getClass().getSimpleName() + " found", e);
}
}
and then inside your test:
expectException(() -> list.sublist(0, 2).get(2), IndexOutOfBoundsException.class);
Benefits: