小编sha*_*rdy的帖子

使用 Java 反射 Junit4 测试异常

我有一个返回异常的函数,我正在 Junit4 中为它编写一个单元测试用例。问题是,reflect.invoke 总是将异常包装在 InvocationTargetException 中,因此无法使用 ExpectedException 类检查异常。

public class Hello {
private void printHello(String msg) {
    if ("hello".equals(msg)) {
        System.out.println("Hello");
    }
        else throw new HeaderException();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void testPrint() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    expectedEx.expect(HeaderException.class);

    Method method = Hello.class.getDeclaredMethod("printHello", String.class);
    method.setAccessible(true);
    method.invoke(Hello.class,"random");

}
Run Code Online (Sandbox Code Playgroud)

输出:

    java.lang.AssertionError: 
Expected: an instance of com.locationguru.CSF.exception.HeaderException
     got: <java.lang.reflect.InvocationTargetException>
 <Click to see difference>

    at org.junit.Assert.assertThat(Assert.java:780)
    at org.junit.Assert.assertThat(Assert.java:738)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:114)
    at org.junit.rules.RunRules.evaluate(RunRules.java:18)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) …
Run Code Online (Sandbox Code Playgroud)

java reflection invoke junit4

6
推荐指数
1
解决办法
1464
查看次数

标签 统计

invoke ×1

java ×1

junit4 ×1

reflection ×1