是否可以通过使用 JUnit 来预期有因有果?
Is it possible to expect a cause with a cause by using JUnit?
如果我预计会出现异常,我可以通过以下方式检查:
exception.expectCause(IsInstanceOf.instanceOf(MyExceptionB.class));
如何检查有因有因的异常?
IE。我有一个异常 MyExceptionA
,原因 MyExceptionB
,原因 MyExceptionC
。我如何检查 MyExceptionC
是否被抛出?
您可以创建一个 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);
}
}
如果我预计会出现异常,我可以通过以下方式检查:
exception.expectCause(IsInstanceOf.instanceOf(MyExceptionB.class));
如何检查有因有因的异常?
IE。我有一个异常 MyExceptionA
,原因 MyExceptionB
,原因 MyExceptionC
。我如何检查 MyExceptionC
是否被抛出?
您可以创建一个 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);
}
}