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?

Jerikc XIONG
  • 3,517
  • 5
  • 42
  • 71
  • Adding to the (correct) answer from @rgettman: You should test exceptions with JUnit's [`ExpectedException`](http://junit.org/apidocs/org/junit/rules/ExpectedException.html). – Seelenvirtuose May 22 '15 at 16:37

1 Answers1

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 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`](http://junit.org/apidocs/org/junit/rules/ExpectedException.html) rule. – Seelenvirtuose May 22 '15 at 16:39
  • 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. – Don Roby May 22 '15 at 16:41
  • @Seelenvirtuose Yes, I think your suggestion is good. – Jerikc XIONG May 22 '15 at 16:41
  • @Seelenvirtuose Yes, that's better than going back to old style. – Don Roby May 22 '15 at 16:43
  • 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) . – Jerikc XIONG May 22 '15 at 17:08