PHPでprivateメソッドをテストしやすくする - Qiitaというのを書いたんですが、毎回元クラスを継承してテスト用クラスを作成するのも面倒だなぁと思ったので、privateやprotectedメソッドにアクセスできるようにするラッパークラスを作ってみました。
class TestingWrapper {
protected $wrappedInstance;
public function __construct($wrappedInstance){
$this->wrappedInstance = $wrappedInstance;
}
public function __call($methodName, $params)
{
if(substr($methodName,0, 9) == '_testing_'){
$callName = substr($methodName, 9);
$method = new ReflectionMethod($this->wrappedInstance, $callName);
$method->setAccessible(true);
$result = $method->invokeArgs($this->wrappedInstance, $params);
return $result;
}else{
return call_user_func_array(array($this->wrappedInstance, $methodName), $params);
}
}
}
使い方
下記 foo クラスの barメソッドをテストしたいとします。
class foo {
private function bar($a){
return $a . 'bar';
}
}
下記の様に、TestingWarpper
で対象インスタンスをラップして、呼び出したいプライベートメソッドに_testing_
を頭につけて呼び出します。
$foo = new foo();
$fooTesting = new TestingWrapper($foo);
$result = $fooTesting->_testing_bar('StringA');
$this->assertEqual($result, 'StringAbar');