Skip to content

Instantly share code, notes, and snippets.

@jk
Last active August 29, 2015 13:58
Show Gist options
  • Save jk/10358543 to your computer and use it in GitHub Desktop.
Save jk/10358543 to your computer and use it in GitHub Desktop.
Helper method to test private and protected methods with PHPUnit (it's not bound to PHPUnit what so ever)
<?php
class PHPUnitHelper {
/**
* Helps testing private and protected methods on SAC objects
* @param object $class_instance class instance object
* @param $method Method name
* @return mixed method return value
*/
public static function invokePrivateMethod($class_instance, $method_name) {
$method = new ReflectionMethod(get_class($class_instance), $method_name);
$method->setAccessible(true);
return $method->invoke($class_instance);
}
}
class MyProtectiveClass {
protected function revealProtectedSecret() {
return 'Protected Secret';
}
}
$c = new MyProtectiveClass();
// equivalent to $c->revealProtectedSecret() if revealProtectedSecret
// were public instead of protected or private
$secret = PHPUnitHelper::invokePrivateMethod($c, 'revealProtectedSecret');
echo $secret.PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment