JUnit: Possible to ‘expect’ a wrapped exception?

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"));
}

Leave a Comment