Jun 10 2010

Unit Testing Singletons

The Singleton

I would say that I fall into the camp that generally shies away from the use of singletons.  To start, singletons are a form of global state that is to be avoided.  They carry state across the entire execution of the program making both testing and debugging difficult.  It becomes hard to execute tests in isolation because they may modify the state of the singleton in ways that undesirably ties tests to a strict execution order.  Beyond problems with global state, objects that use singletons are highly coupled to the both the way the singleton is instantiated and the way it is implemented.  It isn’t possible to test an object that depends on a singleton without testing (or in someway relying on the behavior of) the singleton as well.   Furthermore, this coupling is hidden from the user of the object.  To correctly interact with the class depending on the singleton, a dependency that is not explicit in its interface, you must often also understand the behavior of the singleton.  In other words, the state and behavior of the singleton can affect the behavior of the depending object as well as transitive side effects. Continue reading