如何在 Junit 测试用例中捕获包裹异常?

How to catch enwrapped exception in Junit test case?

我有一个测试用例

@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)

我不相信有 JUnit 方法可以做到这一点 - 您可能必须在测试中手动完成,例如:

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