1. Overview

In this tutorial, we'll look at different ways to verify exceptions in a JUnit test.

2. Verifying Exceptions using @Test Annotation

Firstly, let's see what the @Test annotation offers.

@Test has the expected attribute where we can define the expected Exception class:

@Test(expected = NullPointerException.class)
public void shouldThrowException() {
    throw new NullPointerException("Value is null");
}

Here, we're defining the exception class on the @Test annotation.

However, further verifications aren't possible with this option. For example, we can't verify exception messages.

3. Verifying Exceptions using ExpectedException Rule

Secondly, we'll look at the ExpectedException rule.

The ExpectedException rule lets us define both the exception class and exception message.

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

@Test
public void shouldThrowException() {
    thrown.expect(NullPointerException.class);
    thrown.expectMessage("Value is null");

    throw new NullPointerException("Value is null");
}

Here, we're specifying the exception class and the message inside the test method. Note that this approach provides additional functionality compared to @Test.

4. Verifying Exceptions using Try/Catch Block

Lastly, if we have custom requirements or don't want to use other options, we can verify the exception type using a try/catch block.

@Test
public void shouldThrowException() {
    try {
        throw new NullPointerException("Value is null");
    } catch (Exception e) {
        if (!(e instanceof NullPointerException)) {
            fail("Unexpected exception");
        }
    }

    fail("Should have thrown exception");
}

Here, we're specifying our expected exception in the catch clause.

5. Summary

In this tutorial, we have explored different ways to verify exceptions in a JUnit test.

Finally, check out the source code for all samples over on Github.