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 testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); }
I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
EqualTo("Actual exception message")); So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert. Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.
3. Test Exception in JUnit 3. As you can see, we use the fail() statement at the end of the catch block so if the code doesn't throw any exception, the test fails. And we catch the expected exception by the catch clause, in which we use assertEquals() methods to assert the exception message.
JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.
It depends on the JUnit version and what assert libraries you use.
The original answer for JUnit <= 4.12
was:
@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
Reference :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With