Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: Possible to 'expect' a wrapped exception?

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?

like image 485
ivan_ivanovich_ivanoff Avatar asked May 15 '09 23:05

ivan_ivanovich_ivanoff


People also ask

How do you expect an exception in JUnit?

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.

How do you assert exception not thrown?

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.

How do I expect an exception in JUnit 5?

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.

How do you deal with try-catch in JUnit?

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.


1 Answers

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")); } 
like image 111
Rowan Avatar answered Sep 24 '22 20:09

Rowan