I know that one can define an 'expected' exception in JUnit, doing:
@Test(expect=MyException.class) public void someMethod() { ... }
But what if there is always same exception thrown, but with different 'nested' causes.
Any suggestions?
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.
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.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
You can just let take JUnit to take care of the Exception by adding it to your method sig: public void someTest() throws Exception. However if you want to catch the Exception yourself to assert it being caugt the example you have given is good to go.
As of JUnit 4.11 you can use the ExpectedException
rule's expectCause()
method:
import static org.hamcrest.CoreMatchers.*; // ... @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void throwsNestedException() throws Exception { expectedException.expectCause(isA(SomeNestedException.class)); throw new ParentException("foo", new SomeNestedException("bar")); }
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