Home » Java » Core Java » Testing Expected Exceptions with JUnit Rules

About Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.

Testing Expected Exceptions with JUnit Rules

This post shows how to test for expected exceptions using JUnit. Let’s start with the following class that we wish to test:

public class Person {
  private final String name;
  private final int age;

   * Creates a person with the specified name and age.
   * @param name the name
   * @param age the age
   * @throws IllegalArgumentException if the age is not greater than zero
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
    if (age <= 0) {
      throw new IllegalArgumentException('Invalid age:' + age);

In the example above, the Person constructor throws an IllegalArgumentException if the age of the person is not greater than zero. There are different ways to test this behaviour:

Approach 1: Use the ExpectedException Rule

This is my favourite approach. The ExpectedException rule allows you to specify, within your test, what exception you are expecting and even what the exception message is. This is shown below:

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class PersonTest {

  public ExpectedException exception = ExpectedException.none();

  public void testExpectedException() {
    exception.expectMessage(containsString('Invalid age'));
    new Person('Joe', -1);

Approach 2: Specify the exception in the @Test annotation

As shown in the code snippet below, you can specify the expected exception in the @Test annotation. The test will pass only if an exception of the specified class is thrown by the test method. Unfortunately, you can’t test the exception message with this approach.

@Test(expected = IllegalArgumentException.class)
public void testExpectedException2() {
  new Person('Joe', -1);

Approach 3: Use a try-catch block

This is the ‘traditional’ approach which was used with old versions of JUnit, before the introduction of annotations and rules. Surround your code in a try-catch clause and test if the exception is thrown. Don’t forget to make the test fail if the exception is not thrown!

public void testExpectedException3() {
  try {
    new Person('Joe', -1);
    fail('Should have thrown an IllegalArgumentException because age is invalid!');
  } catch (IllegalArgumentException e) {
    assertThat(e.getMessage(), containsString('Invalid age'));


Reference: Testing Expected Exceptions with JUnit Rules from our JCG partner Fahd Shariff at the fahd.blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....



  1. Your link to the javadoc for ExpectedException returns a 404.

  2. Am I missing something? Or are all the throws declarations are missing?

    • The examples use IllegalArgumentException which is a RuntimeException and, therefore, does not need to be explicitly declared or surrounded in a try/catch as a checked exception (subclass of Exception) would be.

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.