Don’t use @Test(expected = …)

The one feature of JUnit that I really don’t like is the ability to say that a test is expected to throw a particular exception. Here’s an example:

public class MyClass {

   private final Something something;

   public MyClass(Something something) {
      this.something = something;

   public void doWhatever(String aString) {


public class MyClassTest {

  @Test(expected = NullPointerException.class)
  public void shouldThrowNullPointerExceptionWhenStringIsNull() throws Exception {
    MyClass myClass = new MyClass(null);

This example is not as bad as they can be, but it illustrates the point. The method call will indeed throw a NullPointerException, but the reason won’t be that the string parameter is null – the NPE is thrown because the ‘something’ member is null. The general problem with the ‘expected’ parameter to the @Test annotation is that you don’t know which particular case led to the exception, and general exceptions such as NullPointerException (or, worse RuntimeException, or perhaps some generic exception you use for wrapping all kinds of checked exception in some code) can be thrown for many reasons.
I very much prefer code along these lines:

  public void throwsExceptionWithMeaningfulInformation() throws Exception {
     IOException expected = new IOException("expected");

     when(collaborator).method("some parameter").thenThrow(expected);

     try {
        classUnderTest.methodThatCallsCollaborator("some parameter");
        fail("expected exception");
     catch (WrappingException e) {
        assertThat(e.getCause(), equalTo((Throwable) expected));
        assertThat(e.getMessage(), containsString("some parameter"));
        assertThat(e.getMessage(), containsString("something else the code should report"));

EDIT: based on Dominic’s comment, I now normally prefer the idiom below – the rest of the post still applies, but using @Rule and ExpectedException is more concise and readable. The only thing missing is an easily accessible Matcher<Throwable> that would allow you to match the cause as well. I’ll probably create one, for internal use, at least.

EDIT: JUnit 4.11-SNAPSHOT now has support for cause matching using ExpectedException. :)

  public ExpectedException thrown = ExpectedException.none();

  public void throwsNPEIfSecondParameterIsNull() throws Exception {

     new ClassThatDisallowsNullForTheSecondParameter("hi", null);

Both these idioms give you the ability to verify that you’ve in fact triggered the error you wanted to trigger, and it also gives you the ability to ensure that the code is reporting the problem in a good way by checking the message and cause of the thrown exception. Sure, it requires a little more typing than just using the @Test annotation, but you get that time back the first time that exception is actually thrown and somebody needs to figure out what went wrong. Both of the 2 minutes it took to do the extra typing!


, ,

  1. #1 by Dominic Mitchell on February 7, 2012 - 15:04

    Have you seen the ExpectedException class in newer junit versions? It’s a more refined version of @Test(expected=””).

    • #2 by Petter Måhlén on February 7, 2012 - 20:59

      I was not aware of that – that looks like a more concise way of getting the same functionality that I do through the try/catch idiom. Great tip!

  2. #3 by Kristofer on February 8, 2012 - 20:33

    Another option is using something like assertThrows in mockachino.

    You get neat syntax like this:


    instead of using try-catch.

    It’s part of my mocking framework, but nothing in it actually uses mocks.

    Here’s some example usage:

    The feature itself is really simple, in case you want to duplicate it or extend it (optionally verify exception mesage for instance):

    • #4 by Petter Måhlén on February 9, 2012 - 09:48

      I like that syntax, it’s cleaner than the one you get with the JUnit ExpectedException, I think.

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: