3

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?

Oleksandr
  • 3,574
  • 8
  • 41
  • 78

1 Answers1

4

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);
    }
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72