5

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

 2 years ago
source link: https://blog.jakubholy.net/2011/09/16/junit-tip-verifying-that-an-exception-with-a-particular-message-was-thrown/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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.)
Tags: testing

Are you benefitting from my writing? Consider buying me a coffee or supporting my work via GitHub Sponsors. Thank you! You can also book me for a mentoring / pair-programming session via Codementor or (cheaper) email.

Allow me to write to you!

Let's get in touch! I will occasionally send you a short email with a few links to interesting stuff I found and with summaries of my new blog posts. Max 1-2 emails per month. I read and answer to all replies.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK