The Holy Java

Notes of a passionate Java EE developer

JUnit Tip: Verifying that an Exception with a Particular Message was Thrown

Posted by Jakub Holý on September 16, 2011

JUnit has a hidden treasure which makes it easy to do something we have long longed for – namely not only to verify that an exception of a particular type has been thrown but also that its message contains the expected message. The hidden pearl is the @Rule ExpectedException and its JavaDoc documents well how to use it (slightly modified):

import org.junit.*;
import org.junit.rules.ExpectedException;

public static class HasExpectedException {
        @Rule
        public ExpectedException thrown= ExpectedException.none();

        @Test
        public void throwsNothing() {
            // no exception expected, none thrown: passes.
        }

        @Test
        public void throwsNullPointerExceptionWithMessage() {
                thrown.expect(NullPointerException.class);
                thrown.expectMessage("What happened here?");
                thrown.expectMessage(allOf(containsString("What"), containsString("here")));
                throw new NullPointerException("What happened here?");
        }
 }

(As you might have noticed, it uses Hamcrest matchers; containsString isn’t included directly in junit and thus you’d need junit-dep + hamcrest jars.)

About these ads

6 Responses to “JUnit Tip: Verifying that an Exception with a Particular Message was Thrown”

  1. Tomasz N. said

    ExpectedException is nice, however I found it a bit awkward to first records expectations and then run the actual code. Check out how I prefer to test for exceptions.

  2. Great! BTW the expected exception link points to the wrong class (ExternalResource)

  3. Nice post , clean and concise. As a complement, here a link to some solution I have been developing to extend the checks in case of post condition checking: http://patterngazer.blogspot.com/2011/09/ruling-my-expectations-with-junit.html

  4. As Loren has pointed out at DZone, you should do this only if there is no better way. My response:

    @Tomek Thank you for a good response! @Loren is right that it makes tests brittle and often it might be better to fix the design instead, e.g. creating a custom exception subclass. However there are certainly cases when this doesn’t pay off and using this little dirty check is the best compromise.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: