Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

Monday, October 29, 2012

Unit Testing Runtime Exceptions with JUnit4 and Hamcrest

Junit and Hamcrest make unit testing with Java almost enjoyable. In this post, I show how to unit test Exceptions with JUnit4 and Hamcrest. In this over-simplified example, I'm testing a method that always throws an IllegalArgumentException. In real-life the IllegalArgumentException would only be thrown under special circumstances given certain arguments, and those are the ones you want to test with the unit test.

The basic idea is to surround the method you want to test with a try catch block and pass it an argument that will trigger the IllegalArgumentException to be thrown. The fail method call should never be reached, and if it does the unit test should fail. What should happen is that the IllegalArgumentException is caught, followed by a check for the correct message.

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;

import org.junit.Test;

 * The following example code demonstrates how to unit test Exceptions with JUnit and Hamcrest
public class ExceptionUnitTesting {

  public void test() {

    try {
      fail("Expected exception");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage(), is(equalTo("Argument foo is not valid!")));

   * @param foo
   * @throws IllegalArgumentException - in this test case always
  private void blah(String foo) {

    throw new IllegalArgumentException("Argument foo is not valid!");

Piece of Cake!!!

No comments: