Java, JUnit

Testing exceptions in JUnit

In this post, we will look into testing expected exceptions using JUnit.

Let’s consider the following Employee class:

public class Employee {

    private String firstName;
    private String lastName;
    private int age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {

        if(age > 0) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Invalid Employee Age.");
        }
    }
}

The setAge() method throws an exception when an age less than or equal to zero is passed. There are a couple of approaches to test this method:

Approach 1:

The most straight forward approach is to specify the exception in the @Test annotation. The test will pass only if the expected exception is thrown.

    @Test(expected = IllegalArgumentException.class)
    public void employeeAgeTest() {

        Employee emp = new Employee();
        emp.setAge(0);
    }

Approach 2:

The above approach is useful and straight forward. However, it has its own limitations. For example, you can’t test the value of the message in the exception.

JUnit 4.7 introduced ‘ExpectedException’ rule that addresses the shortcomings of the first approach. The ‘ExpectedException’ rule lets you indicate not only what exception you are expecting, but also the exception message you are expecting.


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

    @Test
    public void employeeAgeTest() {
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("Invalid Employee Age");
        Employee emp = new Employee();
        emp.setAge(0);
    }