Testing for expected exceptions in JUnit

Unit tests are used to verify that a piece of code operates as the developer expects it to. Sometimes, that means checking that the code throws expected exceptions too. JUnit is the standard for unit testing in Java and provides several mechanisms for verifying exceptions were thrown. This article explores the options and their relative merits.
Take the following simple code snippet as an example. As well as writing tests to ensure the canVote() method returns true or false, you should also writes tests to verify that it throws an IllegalArgumentException when expected.

  public class Student {
        public boolean canVote(int age) {
            if (i<=0) throw new IllegalArgumentException("age should be +ve");
            if (i<18) return false;
            else return true;

(Guava preconditions might be more suitable for these argument checks, but the example is still valid).

There are 3 common ways to check that exceptions are thrown, each with their own advantages and disadvantages.

1) @Test(expected…)

The @Test annotation has an optional parameter, “expected”, that allows you to specify a subclass of Throwable. If we wanted to verify that canVote()() method above throws the correct exception, we would write:

    @Test(expected = IllegalArgumentException.class)
    public void canVote_throws_IllegalArgumentException_for_zero_age() {
        Student student = new Student();

Simple and concise, if a little imprecise since it tests that the exception will be thrown somewhere in the method, rather than on a specific line.

2) ExpectedException

To use JUnit’s ExpectedException, first you need to declare the ExpectedException:

    public ExpectedException thrown= ExpectedException.none();

Then you can either use the simpler approach of specifying the expected exception only:

    public void canVote_throws_IllegalArgumentException_for_zero_age() {
        Student student = new Student();

Or can also specify the expected exception message too:

    public void canVote_throws_IllegalArgumentException_for_zero_age() {
        Student student = new Student();
        thrown.expectMessage("age should be +ve");

As well as being able to specify the expected exception message, this ExpectedException approach has the advantage of allowing you to be more precise about where the exception is expected to be thrown. In the above example, an unexpected IllegalArgumentException thrown in the constructor would cause the test to fail since we expected it to be thrown in the canVote() method.

On a side note, it would be nice if there wasn’t a need for the declaration:

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

It just seems like unnecessary noise. It would be nice to just be able to do



 expect(RuntimeException.class, “Expected exception message”)

or at least be able to pass the exception and message in an single call to ExpectedException:

 thrown.expect(IllegalArgumentException.class, “age should be +ve”);

3) Try/catch with assert/fail

Prior to JUnit4, the way to check for exceptions was to use try/catch blocks.

    public void canVote_throws_IllegalArgumentException_for_zero_age() {
        Student student = new Student();
        try {
        } catch (IllegalArgumentException ex) {
            assertThat(ex.getMessage(), containsString("age should be +ve"));
        fail("expected IllegalArgumentException for non +ve age");

Although an older approach, it is still perfectly valid. The main downside is that it is easy to forget to put the fail() after the catch, resulting in false positives if the expected exception is not thrown. I have certainly made this mistake in the past!

In conclusion, there are three main approaches for testing expected exceptions get thrown, each with its own advantages and disadvantages. For me personally, I usually lean towards the ExpectedException approach due to its precision and ability to test the exception message.


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!  

Leave a Reply

+ 1 = seven

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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

20,709 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