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
Junit4 solution with Java8 is to use this function:
public Throwable assertThrows(Class extends Throwable> expectedException, java.util.concurrent.Callable> funky) {
try {
funky.call();
} catch (Throwable e) {
if (expectedException.isInstance(e)) {
return e;
}
throw new AssertionError(
String.format("Expected [%s] to be thrown, but was [%s]", expectedException, e));
}
throw new AssertionError(
String.format("Expected [%s] to be thrown, but nothing was thrown.", expectedException));
}
Usage is then:
assertThrows(ValidationException.class,
() -> finalObject.checkSomething(null));
Note that the only limitation is to use a final
object reference in lambda expression.
This solution allows to continue test assertions instead of expecting thowable at method level using @Test(expected = IndexOutOfBoundsException.class)
solution.