Is it possible to test for multiple exceptions in a single JUnit unit test? I know for a single exception one can use, for example
@Test(expected=IllegalStateException.class)
Now, if I want to test for another exception (say, NullPointerException), can this be done in the same annotation, a different annotation or do I need to write another unit test completely?
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.
Usage. You have to add the ExpectedException rule to your test. This doesn't affect your existing tests (see throwsNothing() ). After specifiying the type of the expected exception your test is successful when such an exception is thrown and it fails if a different or no exception is thrown.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
You really want the test to do one thing, and to test for that. If you're not sure as to which exception is going to be thrown, that doesn't sound like a good test to me.
e.g. (in pseudo-code)
try { badOperation(); /// looks like we succeeded. Not good! Fail the test fail(); } catch (ExpectedException e) { // that's fine } catch (UnexpectedException e) { // that's NOT fine. Fail the test }
so if you want to test that your method throws 2 different exceptions (for 2 sets of inputs), then you'll need 2 tests.
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