Singleton为什么对单位测试不利?
目前,我正在研究有关单身人士或否的讨论,似乎对Singleton的主要批评之一是,很难使用Singleton进行单位测试应用程序,而我正试图弄清楚原因。
我想参考此线程: Singleton类很难测试?
因此,您可以使用依赖注入代替单身人士。我们希望拥有一个mynonsingleton
类,该类实现某些接口,实例化和对象,然后将其传递在> otherclass
的CTOR中。这样,在单元测试中,我们可以使用实现接口的模拟类模拟mynonsingleton
。
现在我的问题:假设在单元测试时,我们有一个单独的应用程序,在该应用程序中,我们使用了测试的类别,我不明白两种方法之间有什么区别?使用mysingleton
- 您可以完全提供mysingleton
的模拟实现,就像您提供的模拟实现一样,该实现实现了与mynonsingleton
实施相同的接口,因此Singleton为什么对单位测试不利?
I'm currently delving into the discussion about Singleton yes or no, and it seems that one of the main criticism about singleton is that it's hard to unit test applications that use singleton, and I'm trying to figure out why.
I want to refer to this thread:
Why is a singleton class hard to test?
In short, the accepted answer there explains that when you have a class OtherClass
that uses a singleton class MySingleton
, and say that the Singleton class's methods does something like write to a file, connect to a database, etc. you don't want to do these things in unit tests, you want to mock out that object.
So instead of singleton, you can use Dependency Injection. We want to have a MyNonSingleton
class that implements some interface, to instantiate and object of it, and pass it in the ctor of OtherClass
. This way, in unit tests, we can mock the MyNonSingleton
with a mock class that implements the interface.
Now my question: Assuming that when unit testing, we have a separate application in which we use the tested-out class, I don't understand what is the difference between the 2 approaches? With MySingleton
- you can provide a mock implementation of MySingleton
exactly as you would provide a mock implementation that implements the same interface that MyNonSingleton
implements, so why is singleton bad for unit tests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论