Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

| Views: 1099
With JUnit 4 you can write tests that expect exceptions being thrown from the code you're testing. This is done by passing a value to the expected property for the @Test annotation. Though this is a huge step up from JUnit 3.x behaviour, it is not very flexible and doesn't let you do very accurate fail case testing.

The @Test annotation is good at checking whether a particular type of exception has been thrown and pretty much nothing else. If you need to be able to check the exception message, it's cause or even the cause message, you need to use a JUnit Rule, specifically the ExpectedException rule.

The code below is expecting JUnit 4.12 and Hamcrest 1.3 libraries. As of version 4.11 JUnit is dependant on Hamcrest 1.3 already.

To set up this rule, the following minimal code is required:
package mypackage;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class MyTest {
public final ExpectedException thrown = ExpectedException.none();

The above sets up the rule in such a way that the no exception is expected. This is the same behaviour as if the rule was not there. I am assuming that fail/pass tests will be mixed in the same test class so expecting every test to throw an exception doesn't make sense, so we overwrite this rule for each test case that does expect an exception being thrown.

Next to set up an accurate exception check, the following additional imports are required...
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.*;

The actual code to check for the correct exception type, message and cause type and cause message is below.
public void testExceptionThrows() throws Exception {
/* check the correct exception type and message */
thrown.expectMessage("My exception message");
/* check exception cause type and cause message */
thrown.expectCause(Matchers.<Throwable> allOf(
hasProperty("message", containsString("My other exception message"))
/* remaining code that causes an exception to be thrown */

If you don't care about the cause message, the expectCause() call can be simplified to the following...
thrown.expectCause(Matchers.<Throwable> instanceOf(MyOtherException.class));

With this you can do very accurate fail scenario tests where exceptions are being thrown. It is more code to write, but very well worth the effort if you want good tests.


Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...