【发布时间】:2015-08-07 15:18:32
【问题描述】:
我有一个测试用例
@Test(expected = IllegalArgumentException.class)
public void test() throws Exception{
..test content...
}
因为我在测试用例中使用了 Java 反射,所以 IllegalArgumentException 被包裹在 InvocationTargetException 中,我如何才能捕获预期的 IllegalArgumentException 而不是 InvocationTargetException。
错误信息显示为
java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.reflect.InvocationTargetException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
【问题讨论】:
-
可能答案已经出来了,但我个人会简单地实现一个自定义 hamcrest 匹配器来检查原因是否为 IllegalArgumentException - 然后使用 ExpectedException 规则来使用它。