如何在Java应用程序中测试私有构造函数? [英] How to test a private constructor in Java application?

查看:80
本文介绍了如何在Java应用程序中测试私有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类包含一堆静态方法,为了确保没有人错误地初始化这个类的实例,我创建了一个私有构造函数:

If a class contains a bunch of static methods, in order to make sure no one by mistake initializes an instance of this class, I made a private constructor:

private Utils() {
}

现在。如果不能看到构造函数,怎么能测试呢?可以完全覆盖测试吗?

Now .. how could this be tested, given that constructor can't be seen? Can this be test covered at all?

推荐答案

使用反射,可以调用私有构造函数:

Using reflection, you can invoke a private constructor:

Constructor<Util> c = Utils.class.getDeclaredConstructor();
c.setAccessible(true);
Utils u = c.newInstance(); // Hello sailor

然而,你甚至可以做到这一点:

However, you can make even that not possible:

private Utils() {
    throw new UnsupportedOperationException();
}

通过在构造函数中抛出异常,可以防止所有尝试。

By throwing an exception in the constructor, you prevent all attempts.



我会让班级本身最终,只是因为:

public final class Utils {
    private Utils() {
        throw new UnsupportedOperationException();
    }
}

这篇关于如何在Java应用程序中测试私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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