Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for multiple exceptions with JUnit 4 annotations

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?

like image 626
phantom-99w Avatar asked Sep 11 '09 10:09

phantom-99w


People also ask

How does JUnit handle multiple exceptions?

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.

How do you use ExpectedException?

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.

How do you assert if an 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.


1 Answers

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.

like image 107
Brian Agnew Avatar answered Sep 23 '22 20:09

Brian Agnew