1 year ago
#351488
YoavKlein
Why is Singleton bad for unit tests?
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?
c++
singleton
0 Answers
Your Answer