Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you assert that a certain exception is thrown in JUnit 4 tests?

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.

like image 357
SCdF Avatar asked Oct 01 '08 06:10

SCdF


People also ask

How do you assert throwing exception?

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.

How do I check if an exception is caught JUnit?

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.

How can you use JUnit for testing a code that throws a desired exception?

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.


1 Answers

It depends on the JUnit version and what assert libraries you use.

  • For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984
  • If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984

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 :

  • JUnit Test-FAQ
like image 51
skaffman Avatar answered Oct 08 '22 08:10

skaffman