Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

QaFoo Blog:
Refactoring Singleton Usage to get Testable Code
Jul 11, 2017 @ 12:22:07

The QaFoo.com blog has a new post sharing a helpful hint on refactoring singletons to make them more testable. Singletons and notoriously difficult to test due to how it can potentially return an unexpected version of an object.

So your code base is littered with singletons and using them? Don't worry, you can start refactoring them out of your code base class by class and introduce increased testability at every step. This strategy is very simple to implement and the probability of breaking your code is very low, especially when you are becoming more experienced with this technique.

They give an example of a service class that uses a singleton to get an instance of the Solarium_Client class via a static method call. They show how to refactor this out into a separate method and then use the "lazy initialization" pattern to only use the singleton if the property isn't already defined. This then allows you to use a setter to inject your own client during testing (a mock most likely).

tagged: refactor testing unittest mock singleton property lazy initialization

Link: https://qafoo.com/blog/107_refactoring_singletons_testability.html