DEV Community

Discussion on: Improve your PHP code testability

Collapse
 
doekenorg profile image
Doeke Norg

Nice article and a powerful technique.

In case of a protected variable I would however choose to extend the class and make the variable public, or set a test double on that variable. Then use that code for testing. Using reflection makes this so magic and hard to understand. And it also hints to an error in the code, as you already noted.

You can also update the constructor and inject an instance with null as a default, and then set the normal instance with: $this->unacessibleDependency = $unacessibleDependency ?? new UnacessibleDependency(). That way you can inject a test double in the test and keep the existing implantation.

Knowing about this reflection approach is very useful in some cases. But I would highly recommend against it.