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 {

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

  @Test
  public void testExpectedException() {
    exception.expect(IllegalArgumentException.class);
    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!

@Test
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.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

2 Responses to "Testing Expected Exceptions with JUnit Rules"

  1. Wesley Womack says:

    Your link to the javadoc for ExpectedException returns a 404.

  2. Joel says:

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

Leave a Reply


× 8 = sixteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books