LoginSignup
4
3

More than 5 years have passed since last update.

PHPでprivateメソッドをテストしやすくするTestingWrapper

Posted at

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');
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3