Last active
August 25, 2022 14:26
-
-
Save royteusink/b2ed12005d76716a7d28f2d333efc6da to your computer and use it in GitHub Desktop.
Laravel PHP Unit test private and protected variable or function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('testShadow')) { | |
/** | |
* Magically access a private or protected variable or methods from an instance of a class. | |
* Use this only in UnitTests | |
* | |
* @param mixed $instance Instance of a class | |
* @param string $name Name of the inaccessible variable or method | |
* @return mixed variable | |
*/ | |
function testShadow($instance, string $name, ...$args) | |
{ | |
return (fn() => isset($this->$name) ? $this->$name : $this->$name(...$args))->call($instance); | |
} | |
} | |
testShadow(new SomeClass, 'variableName'); | |
testShadow(new SomeClass, 'methodName', 1, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment