DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > JUnit Tip: Verifying that an Exception with a Particular Message was Thrown

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

Jakub Holý user avatar by
Jakub Holý
·
Sep. 23, 11 · Java Zone · Interview
Like (0)
Save
Tweet
8.53K Views

Join the DZone community and get the full member experience.

Join For Free

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/

JUnit

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Autowiring in Spring
  • 5 Steps to Strengthen API Security
  • 12 Kick-Ass Software Prototyping and Mockup Tools
  • ETL, ELT, and Reverse ETL

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo