Script Analytics

2014/02/10

How to test exception with JUnit

Testing that an exception has been thrown in JUnit test was painfull until I discovered ExpectedException rule.
Here is a brief overview of exception test mechanisms available in JUnit.

Old-style assertion :
@Test
public void should_throw_IndexOutOfBoundsException() {
  try {
    List<Object> emptyList = new ArrayList<Object>();
    Object o = emptyList.get(0);
    fail("An IndexOutOfBoundsException should have been thrown");
  } catch(IndexOutOfBoundsException e) {
    Assert.assertEquals("Index: 0, Size: 0", e.getMessage());
  }
}
Effective but not so elegant...

From JUnit 4 :
@Test(expected=IndexOutOfBoundsException.class)
public void should_throw_IndexOutOfBoundsException() {
  List<Object> emptyList = new ArrayList<Object>();
  Object o = emptyList.get(0);
}
This is concise however you are not able to check the exception's message.

From JUnit 4.7 :
@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void should_throw_IndexOutOfBoundsException() {
  exception.expect(IndexOutOfBoundsException.class);
  exception.expectMessage("Index: 0, Size: 0");

  List<Object> emptyList = new ArrayList<Object>();
  Object o = emptyList.get(0);
}
This rule defines a default contract for all your tests, they must not throw an exception.
You can override this contract at will if you need to verify that an exception will be thrown during the test.

No comments:

Post a Comment