Unstable Terrain

Software development in the real world

Testing JUnit 4 Exception Messages

leave a comment »

In previous years, I have tested exceptions in JUnit tests using variations on the

try {
} catch (Exception expected) {
  assertEquals("Invalid Number of Foos", expected.getMessage());

pattern. Various upgrades such as codifying it into an AssertThrows class and checking the correct exception type have helped but it was a pretty ordinary solution.

Changing to JUnit 4 allowed for the annotation below:


… but testing the exception message remained ugly.

JUnit 4.7 has a neat upgrade: testing that thrown exceptions have particular messages.

For example:

public class BuilderTest {
  public ExpectedException thrown = ExpectedException.none();

  public void invalidMessagesShouldThrowAutoPopulateException() {
    thrown.expectMessage("too many autopopulate errors");


It also accepts a Hamcrest-style matcher if you want to do something more complicated.


Written by Trent

February 18, 2011 at 4:19 pm

Posted in Software Development, Tools

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: