Is it possible for that a JUnit test succeeds if it returns the expected exception?
Can you tell me how to implements such test by a simplified example?
Thanks a lot.
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. I'll add that I think the question here is one of style: catch-and-fail, or throw? Normally, best practice avoids "throws Exception".
If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.
Both failure and error in JUnit tests indicate an undesired situation, but their semantics are different. Failures notify of an invalid test result, errors indicate an unexpected test execution. Also, please check out the example code at GitHub. November Discount Launch 2022 – Bottom.
Why cant you just catch your exception in the test? There are different ways of doing this. Like annotating @Test(expected = DataAccessException.class)
and that needs to be used on a case by case basis too. But below way is what i would propose.
public class TestCase{
@Test
public void method1_test_expectException () {
try{
// invoke the method under test...
Assert.fail("Should have thrown an exception");
// This above line would only be reached if it doesnt throw an exception thus failing your test.
}
catch(<your expected exception> e){
Assert.assertEquals(e.getcode(), somce error code);
}
}
The proper way to achieve that, in JUnit4, is to use an ExpectedException public field, annotated with @Rule
, as follows:
import org.junit.rules.ExpectedException;
import org.junit.Rule;
import org.junit.Test;
public class MyTestClass {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void aTestThatSucceedsOnlyIfRuntimeExceptionIsThrown() {
thrown.expect(RuntimeException.class);
// invoke code to be tested...
}
}
Note that you also use @Test(expected=RuntimeException.class)
but the former is usually considered superior for the following reason: it allows you to specify the exact point in your test where an exception should be thrown. If you use the latter the test will succeed if any line inside it throws an exception (of the expected type) which is often not what you want.
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