测试反射newInstance异常 [英] Testing reflection newInstance exception

查看:203
本文介绍了测试反射newInstance异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我使用的反射非常有限:

I'm using a very limited set of reflection in this piece of code:

public NetworkClient createNetworkClient() {
    try {
        return (NetworkClient) getNetworkClientClass().getConstructors()[0].newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

如何测试(使用单元测试)newInstance() 抛出InvocationTargetException(以及其他异常)?

How can I test (using unit testing) that newInstance() throw an InvocationTargetException (and the other exception) ?

我目前正在将Mockito和Hamcrest用于UT的其余部分.

I'm currently using Mockito and Hamcrest for the rest of the UT.

推荐答案

最简单的方法可以是创建一个静态嵌套类,该类在您的测试类中扩展NetworkClient,该类将在其构造函数中抛出一个Exception,如下所示:

The simplest approach can be to create a static nested class that extends NetworkClient in your test class that will throw an Exception in its constructor like this:

public class MyTest {
    public static class MyFailingNetworkClient extends NetworkClient {
        public MyFailingNetworkClient() {
            throw new RuntimeException("Cannot create this object");
        }
    }
    ...
}

然后在您的测试用例中,可以使用Mokito使getNetworkClientClass()返回MyFailingNetworkClient.class (假设它不能通过简单的设置器完成),如下所示:

Then in your test case, you can use Mokito to make getNetworkClientClass() returns MyFailingNetworkClient.class (assuming that it cannot be done with a simple setter) as next:

MyObject object = spy(new MyObject());
when(object.getNetworkClientClass()).thenReturn(
    MyFailingNetworkClient.class
);

这篇关于测试反射newInstance异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆