9

I'm using JUnit 4.11.

Eclipse Version: Luna Service Release 2 (4.4.2)

I need do the exception test. The code maybe like this:

// src code
public void myMethod throws MyException {
    ...
    throw new MyException(msg);
    ...
}

// test code
@Test (expected = MyException.class)
public void testMyMethod() {
    try {
        myMethod();
        fail();
    } catch (MyException e) {
        assertEquals(expectedStr, e.getMessage());
    }
}

But the test always fail, where am i wrong?

1
  • Adding to the (correct) answer from @rgettman: You should test exceptions with JUnit's ExpectedException. Commented May 22, 2015 at 16:37

1 Answer 1

6

When you provide an expected exception to the Test annotation, the test will only succeed if the exception expected is thrown from the test method. However, you catch the exception before it propagates out of the method.

It looks like you want to test the exception message too, so re-throw the exception e to satisfy the test. Depending on whether it's checked, you may need a throws clause on the method.

Sign up to request clarification or add additional context in comments.

5 Comments

I would not recommend to catch the exception just to test the message with rethrowing it for satisfying the test. It's better to use the ExpectedException rule.
If you want to test the message as well as the fact that the exception is thrown, you can simply remove the expected = MyException.class and leave the rest of the code as it is here. This was how you tested exceptions before that was added to JUnit anyway, and it still works.
@Seelenvirtuose Yes, I think your suggestion is good.
@Seelenvirtuose Yes, that's better than going back to old style.
But how about only test whether there is a exception thrown? If i don't catch the exception, i cannot run the project by the eclipse. That means, i must catch the exception. So it doesn't make sense about the @Test (expected = MyException.class) .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.