Testing for Exceptions

Jakob Jenkov
Last update: 2014-05-24

Sometimes you may want to test that your code throws the right exceptions when given invalid input, or if executed in an invalid state. There are two ways to do this.

The first way to signal that it is expected that the test method results in an exception being thrown, is to add the expected attribute to the @Test annotation, like this:

@Test(expected = IllegalArgumentException.class)
public void testForExceptions1() {
    MyUnit myUnit = new MyUnit();

    myUnit.throwIllegalArgumentException();
}

Notice how the expected attribute is set to IllegalArgumentException.class. This signals to the test runner, that when it executes this test method it is expected that an IllegalArgumentException is thrown. If no IllegalArgumentException is thrown, the test fails.

The second way is to wrap the code you expect to throw an exception in a try-catch block, like this:

@Test
public void testForExceptions2() {
    MyUnit myUnit = new MyUnit();

    try{
        myUnit.throwIllegalArgumentException();

        fail("expected IllegalArgumentException");

    } catch(IllegalArgumentException e){
        //ignore, this exception is expected.
    }

Notice the fail() method call after the call to myUnit.throwIllegalArgumentException(). If the throwIllegalArgumentException() method returns normall, then this fail() call is executed, causing the test to fail.

Correspondingly, if the throwIllegalArgumentException() method throws the expected IllegalArgumentException, it is caught in the catch-clause, and ignored. The test continues.

Which of the two methods you want to use is up to you. Of course, if you need to test for multiple exceptions within the same test method, the first way won't work. Remember, the first way aborts the test method when the expected exception is thrown. You will then have to use the second way to test for exceptions, where the test method continues when the expected exception is thrown.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next