Exception testing

Methods often throw exceptions but how do you test that your code throws the right exception? This example will show three different ways on how to validate or test for exceptions.

Expected NullPointerException

The first approach is to add the expected clause in the @Test method. The expected parameter is optional and if specified is a Throwable which cause the test method to succeed if an exception is caused within the method.

@Test(expected = NullPointerException.class)
public void check_for_nullpointer_exception_junit() {

    String test = null;

    if (test.length() == 5) {}
}

Expected IndexOutOfBoundsException

@Test(expected = IndexOutOfBoundsException.class)
public void check_for_indexoutofbounds_exception_junit() {
    new ArrayList<String>().get(0);
}

Exception w/ try/catch

The second approach is to use the fail assertion which will fail a test with a given exception.

@Test
public void test_for_exception_try_catch_junit() {
    try {
        new ArrayList<String>().get(0);
        fail("Expected an IndexOutOfBoundsException to be thrown");

    } catch (IndexOutOfBoundsException e) {
        assertThat(
                e.getMessage(),
                isA(String.class));
    }
}

Exception w/ Rule

The third approach is to use the Junit @Rule.

@Rule public ExpectedException thrown = ExpectedException.none();

@Test
public void test_for_exception_with_rule_junit() throws IndexOutOfBoundsException {
    List<String> list = new ArrayList<String>();

    thrown.expect(IndexOutOfBoundsException.class);
    thrown.expectMessage("Index: 0, Size: 0");
    list.get(0); // execution will never get past this line
}