Steve Chambers Steve Chambers - 1 month ago 7
Java Question

How to verify the details of exceptions thrown in JUnit tests?

I'm writing a JUnit/Mockito test where an exception is expected to be thrown. Of course I can just do this:

@Test(expected=IllegalArgumentException.class)


But it doesn't let me to do anything else after it was thrown. So I was thinking maybe something more like:

Exception actualEx = null;
try {
// Act
sut.doStuff();
} catch (final Exception ex) {
actualEx = ex;
}
// Assert
assertTrue(IllegalArgumentException.class.equals(actualEx.getClass()));
// ... perhaps verify the exception details
verifyNoMoreInteractions(mockObject);


This seems pretty ugly and feels like it could be improved - is there a better way?

Answer

I think you should be consistent throughout your project - although there are three or four different ways to solve this problem, you absolutely should not try to use all of them.

Since the ExpectedException mechanism is the most powerful and most versatile way, I would recommend you learn to use it. Its advantages include the following.

  • It's easy to check both the type of the thrown exception and its message.
  • You can do more sophisticated matching on the exception if you need to.
  • You can check exactly which line of your test throws the exception, by placing the expect call immediately before the line that you expect to throw the exception.

At the risk of sounding like a shampoo advertisement - now that I've used ExpectedException, I wouldn't use anything else!