Search code examples
javajunitexpected-exception

Is it possible to expect a cause with a cause by using JUnit?


If I expect an exception with some cause I can check it with:

exception.expectCause(IsInstanceOf.instanceOf(MyExceptionB.class));

How do I check an exception with a cause with a cause? I.e. I have an exception MyExceptionA with a cause MyExceptionB with a cause MyExceptionC. How do I check that MyExceptionC was thrown?


Solution

  • You can create an hasCause matcher and use it with ExpectedException

    import org.hamcrest.Matcher;
    import org.hamcrest.Matchers;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ExpectedException;
    
    import static org.hamcrest.Matchers.*;
    import static org.junit.rules.ExpectedException.none;
    
    public class XTest {
    
        @Rule
        public final ExpectedException thrown = none();
    
        @Test
        public void any() {
            thrown.expect(
                    hasCause(hasCause(instanceOf(RuntimeException.class))));
            throw new RuntimeException(
                    new RuntimeException(
                            new RuntimeException("dummy message")
                    )
            );
        }
    
        private Matcher hasCause(Matcher matcher) {
            return Matchers.hasProperty("cause", matcher);
        }
    }