Steve Chambers Steve Chambers - 1 year ago 72
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:


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
} catch (final Exception ex) {
actualEx = ex;
// Assert
// ... perhaps verify the exception details

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

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download