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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice article and a powerful technique.
In case of a
protected
variable I would however choose to extend the class and make the variablepublic
, 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.