On the QaFoo blog today Kore Nordmann has posted a suggestion that could make your unit testing life simpler: get rid of statics (variables, methods, etc).
When people start (unit-)testing their code one of the worst problems to tackle are static calls. How can we refactor static calls out of an existing application without breaking the code and while producing new features? How can we get rid of this big test impediment?
They illustrate the main problem with a simple
UserService class that contains a static function which, in turn, uses static calls to a
Cache and a
DB class. The major issue is that, when the static
getUser method is called there's not a way to mock the
DB classes, resulting in the actual handlers being called. They offer three things you can do to help refactor away from using static methods:
- Replaceable Singletons
- Service Locator
- Dependency Injection
For each item on the list a brief explanation is provided of what it is and how it helps you get away from the singletons scattered throughout your codebase (and how it makes things easier to test).