Ok, why singletons are bad you can read here: What is so bad about singletons?
Specifically for testing: A typical singleton pattern looks like this
class MyClass
{
private static MyClass m_Instance = new MyClass();
public static MyClass Instance
{
get { return m_Instance; }
}
}
Now imagine you have to run a whole bunch of tests all involving the MyClass.Instance
. This class carries around a state and you usually need to have to have a way to reset it between tests so that each test can start with a clean initial state. Now you can add a Reset()
method but that means you add code to your class just for the purpose of being able to test it which is not desirable.
What to use instead: Well, the singleton in itself is not really the bad thing. The problem it leads to is that it makes it easy to write code like this:
class SomeClass
{
public void SomeMethod()
{
...
MyClass.Instance.DoSomething();
}
}
Now you have created an implicit dependency on the singleton instance you cannot easily break. One approach which solves this problem is via dependency injection (which was already mentioned):
class SomeClass
{
public SomeClass(MyClass myClass)
{
m_MyClass = myClass;
}
public void SomeMethod()
{
...
m_MyClass.DoSomething();
}
}
and you can do:
var someClass = new SomeClass(MyClass.Instance);
in your program and
var someClass = new SomeClass(new MyClass());
for testing.
So singletons are not that bad and sometimes the right tool for the right job, however you need to be careful of how you use them.