Exception testing in JUnit

Here`s how to check if an exception occurs when running a test.

Method using Annotation

Annotation can be used to test whether an exception has occurred. You can specify the expected exception when executing the code like @Test(expected = Exception). In the code below, the test will pass if a NullPointerException is thrown, otherwise it will fail.

@Test(expected = NullPointerException.class)
public void testExceptionThrown() {
    String str = null;

    str.contains("a");
}

Method using ExpectedException Rule

You can test whether an Exception occurs using a Rule called ExpectedException.

If the test below throws a NullPointerException, the test will pass. You can specify the exception that you expect to occur in the expect() method.

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

@Test
public void testExceptionThrown() {
    exceptionRule.expect(NullPointerException.class);

    String str = null;
    str.contains("a");
}

Check the message contents of the Exception

If the code above throws a NullPointerException, the test will pass, but sometimes its hard to guarantee that the code Im expecting throws an Exception. In this case, you can test more accurately by checking the contents of the message of the exception.

In the code below, the test only passes when the message of NullPointerException is "Null object is invoked".

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

@Test
public void testExceptionThrown2() {
    exceptionRule.expect(NullPointerException.class);
    exceptionRule.expectMessage("Null object is invoked");

    throw new NullPointerException("Null object is invoked");
}

If a NullPointerException of another message occurs as shown below, the test fails.

@Test
public void testExceptionThrown2() {
    exceptionRule.expect(NullPointerException.class);
    exceptionRule.expectMessage("Null object is invoked");

    throw new NullPointerException("Null object");
}

The failure message will look something like this:

java.lang.AssertionError:
Expected: (an instance of java.lang.NullPointerException and exception with message a string containing "Null object is invoked")
     but: exception with message a string containing "Null object is invoked" message was "Null object"

How to use try-catch

You can test whether an exception is raised using try-catch as shown below. When an exception occurs, it goes to catch, so fail() is not called and the test passes. If no exception occurs, fail() is called and the test fails.

@Test
public void testExceptionThrown3() {
    try {
        String str = null;
        str.contains("a");

        fail();
    } catch (NullPointerException e) {
        // pass
    }
}
codechachaCopyright ©2019 codechacha