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 {
  doSomething();
  fail();
} 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:

@Test(expected=IllegalArgumentException.class)

… 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 {
  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public void invalidMessagesShouldThrowAutoPopulateException() {
    thrown.expect(InternalAssertionError.class);
    thrown.expectMessage("too many autopopulate errors");

    builder.build(createGroupWithTooManyAutoPopulateAnnotations());
  }
}

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 comment