Skip to content

Instantly share code, notes, and snippets.

@legend80s
Created July 18, 2017 06:34
Show Gist options
  • Save legend80s/c48c109f10007be1f488fb0b30f8ffb7 to your computer and use it in GitHub Desktop.
Save legend80s/c48c109f10007be1f488fb0b30f8ffb7 to your computer and use it in GitHub Desktop.
Call protected/private static method of a class. Used usually in Unit Test.
<?php
trait MethodInvoker {
/**
* Call protected/private static method of a class.
*
* @param string $class - class name that we will run method on
* @param string $methodName - method name to call
* @param array $parameter - parameter to pass into method
*
* @return mixed - original method's return
*/
public static function invokeStaticMethod($class, $methodName)
{
$reflectionClass = new ReflectionClass($class);
$method = $reflectionClass->getMethod($methodName);
$method->setAccessible(true);
// get all the parameters after $methodName
$parameters = array_slice(func_get_args(), 2);
return $method->invokeArgs(null, $parameters);
}
}
@legend80s
Copy link
Author

legend80s commented Jul 18, 2017

Example:

class OpenSearch_AppTest extends PHPUnit_Framework_TestCase {
    use MethodInvoker;

    public function testGetIndexConfigs() {
        $expected = [];
        $actual = $this->invokeStaticMethod('OpenSearch_App', 'getIndexConfigs', $searchFields);

        $this->assertEquals($expected, $actual);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment