PHPUnit testing singleton dependencies

Unit testing should be simple, but when you have a code base which uses static methods, singletons and a lack of dependency injection, you can run into some serious problems.

The key to writing maintainable and testable code is dependency injection. Without dependency injection, our objects have to rely on systems that may or may not be under our control. We want our unit tests to be executable in an environment which does require a database or a file system or another systems API etc. Dependency injection allows us to provide mocks of these external and frankly irrelevant sources. The mocks will simply tell us what we want to hear and then we can test our own system with this data. Normally we would use PHPUnits getMockBuilder method to create mock objects, this however cannot be used in the case of a singleton for a few reasons:

Continue reading