Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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.)

From http://theholyjava.wordpress.com/2011/09/16/junit-tip-verifying-that-an-exception-with-a-particular-message-was-thrown/

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}