Edit: Not JUnit 4 available at this time.
Hi there,
I have a question about \"smart\" exception testing with JUnit. At this time, I do it like this:
In Java 8, you can use lambda expressions to get tighter control over when the exception is thrown. If you use the annotations method then you're only asserting that the exception is thrown somewhere in the test method. If you're executing more than one line of code in the test then you risk your test passing when it should fail. Java 8 solution is something like this.
static void expectException(Class type, Runnable runnable) {
try {
runnable.run()
} catch (Exception ex) {
assertTrue(ex.getClass().equals(type));
return;
}
assertTrue(false);
}
Usage:
@Test
public void test()
MyClass foo = new MyClass();
// other setup code here ....
expectException(MyException.class, () -> foo.bar());
}