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?
You would have to write a different unit test for each way the method can fail. So if the method legitimately throw two exceptions then you need two tests set up to force the method of throwing each exception. But under one set of data is can only fail in one way.
Example Failure When writing unit tests with JUnit, there will likely be situations when tests fail. One possibility is that our code does not meet its test criteria. That means one or more test cases fail due to assertions not being fulfilled.
The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With