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

QaFoo Blog:
Getting Rid of static
Jan 12, 2017 @ 16:46:41

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 Cache or DB classes, resulting in the actual handlers being called. They offer three things you can do to help refactor away from using static methods:

  1. Replaceable Singletons
  2. Service Locator
  3. 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).

tagged: static refactor unittest testing singleton servicelocator dependencyinjection

Link: https://qafoo.com/blog/094_getting_rid_of_static.html


Trending Topics: