使用JUnit测试的不同Singleton实例 [英] Different Singleton instances with JUnit tests
问题描述
我有一个独立的单例,该单例成功通过了测试.但是,对于一组测试,此操作将失败,因为一旦定义了单例,将不允许重置实例.
I have a standalone singleton which successfully passes the test. But with a group of tests this fails since once a singleton is defined it does not allow to reset the instance.
关于如何解决这个问题的任何想法?
Any ideas about how to go about this?
推荐答案
不要使用单例.
具体来说,单例和全局变量之间的唯一区别是单例尝试强制执行单个实例(例如,通过将构造函数设为私有).
Specifically, the only difference between a singleton and a global variable is that the singleton tries to enforce a single instance (by making the constructor private, for example).
相反,将构造方法公开,并使用新实例编写测试.在您的实际程序中,使用getInstance()
获取规范的全局实例(或使用IOC容器).
Instead, make the constructor public and write tests using new instances. In your actual program, use getInstance()
to get the canonical global instance (or use an IOC container).
请记住,信箱是病理骗子
如果您仍然对Singleton的想法不太满意,则可以添加一个公共(和静态)工厂方法来创建实例,而该实例不能以偶然的方式使用,而不是将构造方法公开. :
If you're still too comfortable with the idea of a Singleton, instead of making the constructor public you can add a public (and static) factory method to create instances in a way that can't be used by accident, e.g.:
public static MyClass TEST_CreateInstance() {
return new MyClass();
}
这篇关于使用JUnit测试的不同Singleton实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!