Skip to content

Instantly share code, notes, and snippets.

@royteusink
Last active August 25, 2022 14:26
Show Gist options
  • Save royteusink/b2ed12005d76716a7d28f2d333efc6da to your computer and use it in GitHub Desktop.
Save royteusink/b2ed12005d76716a7d28f2d333efc6da to your computer and use it in GitHub Desktop.
Laravel PHP Unit test private and protected variable or function
<?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