如何在 Java 应用程序中测试私有构造函数? [英] How to test a private constructor in Java application?
本文介绍了如何在 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.
我也会使类本身 final
,只是因为":
public final class Utils {
private Utils() {
throw new UnsupportedOperationException();
}
}
这篇关于如何在 Java 应用程序中测试私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文