在寫單元測試時,有時候需要測試
A class 的 protected or private method
,可以使用
Class Reflection
來做,
而不是去改成public,破壞封裝
。
在
laravel 的 abstract TestCase class 中添加一個方法就行:
/**
* Call protected or private method of a class.
*
* @param object $object instantiated object that we will run method on.
* @param string $method_name method name to call
* @param array $parameters array of parameters to pass into method.
*
* @return mixed Method return.
*/
protected function invokeNonPublicMethod($object, string $method_name, ...$parameters)
{
$reflection = new ReflectionClass(get_class($object));
$method = $reflection->getMethod($method_name);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
複制
然後在
test case
中這樣寫測試就行:
final AccountTest extends TestCase
{
public function testValue()
{
$account = new Account()
// actual
$values = $this->invokeNonPublicMethod($account, 'privateMethod', [1, 2, 3]);
// $values = $this->invokeNonPublicMethod($account, 'protectedMethod', [2, 3, 4]);
// assert
...
}
}
複制