【问题标题】:How to catch enwrapped exception in Junit test case? [duplicate]如何在 Junit 测试用例中捕获封装异常? [复制]
【发布时间】: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 规则来使用它。

标签: java junit


【解决方案1】:

我不相信有 JUnit 的方式来做这件事——你可能必须在测试中手动做,例如:

@Test
public void test() {
    try {
       runTest();
       fail();
    } catch (InvocationTargetException x) {
       if( ! (x.getCause() instanceof IllegalArgumentException)) {
           fail();
       }
    }
}

【讨论】:

  • 使用assertTrue( expected.getCause() instanceof IllegalArgumentException );可以使断言更清晰
  • 丑得要命。使用 ExpectedException 规则(我们称之为“expectedException”),您可以简单地编写...expectedException.expect( hasCause( IllegalArgumentException.class ));,只需实现 HasCause hamcrest 匹配器。
  • 好吧,如果你想加入其他库,那么code.google.com/p/catch-exception 会更整洁。
  • 不错的建议,喜欢。
【解决方案2】:

您可以捕获 InvocationTargetException 并抛出 IllegalArgumentException。

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2021-01-21
    • 2016-12-07
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多