3

如果我期望由于某种原因出现异常,我可以通过以下方式进行检查:

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

如何检查有原因的异常?即我有一个有MyExceptionA原因的例外。如何检查是否被抛出?MyExceptionBMyExceptionCMyExceptionC

4

1 回答 1

4

您可以创建一个hasCause匹配器并将其与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);
    }
}
于 2018-07-02T21:13:39.063 回答