by Rafał Borowiec

Menu

Saturday, March 1, 2014

There are different ways of handling exceptions in JUnit tests. As I wrote in one of my previous posts, my preferable way is using org.junit.rules.ExpectedException rule. Basically, rules are used as an alternative (or an addition) to methods annotated with org.junit.Before, org.junit.After, org.junit.BeforeClass, or org.junit.AfterClass, but they are more powerful, and more easily shared between projects and classes. In this post I will show more advanced usage of org.junit.rules.ExpectedException rule.

Verify the exception message

Standard JUnit's org.junit.Test annotation offers expected attribute that allows you specifying the a Throwable to cause a test method to succeed if an exception of the specified class is thrown by the method. In many cases this seems enough, but if you want to verify an exception message - you must find other way. With ExpectedException is pretty straightforward:

As you can see both exceptions thrown by a method are RuntimeExceptions, so in case we do not check the message, we are not 100% sure which exception will be thrown by a method. The following tests will pass:

Checking for the message in an exception will solve the problem and make sure you are verifying a wanted exception. This is already an advantage over expected attribute of @Test annotated methods.

But what if, you need to verify an exception message in a more sophisticated way? ExpectedException allows you that by providing a Hamcrest matcher to expectMessage method (instead of a String). Let's look at the example below:

Verify the exception object

Matching messages may not be enough in certain scenarios. You may have an exception with custom methods and you want to verify them too. No problem at all. ExpectedException allows that with expect method that takes matcher.

Please note, that I implemented both describeTo and describeMismatchSafely methods of TypeSafeMatcher. I need them to produce nicely looking error messages when the test fails. Have a look at an example below: