LoginSignup
11
12

More than 5 years have passed since last update.

PHPUnitのMockクラスで、メソッドを自在にスタブ化する

Posted at

確認環境

  • PHP 5.3
  • PHPUnit 4.4.2

returnValueMapを使うべし

引数が複数の時

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnValueMapStub()
    {
        $mock = $this->getMockBuilder('SomeClass')
            ->getMock();

        // 値を返すためのマップ
        // 配列の先頭から第一引数、第二、、、として、最後にダミーの返却値
        // この場合は引数が3つ
        $map = array(
            array('a', 'b', 'c', 'd'),
            array('e', 'f', 'g', 'h'),
        );

        $mock
            ->method('doSomething')
            ->will($this->returnValueMap($map));

        // $mock->doSomething() は、渡した引数に応じて異なる値を返します
        $this->assertEquals('d', $stub->doSomething('a', 'b', 'c'));
        $this->assertEquals('h', $stub->doSomething('e', 'f', 'g'));
    }
}

ドキュメント のままです。

引数が単数の場合

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnValueMapStub()
    {
        $mock = $this->getMockBuilder('SomeClass')
            ->getMock();

        // 値を返すためのマップ
        // 先頭は同じく引数、3つ目の要素がダミーの返却値となる
        $map = array(
            array('a', array(), 'd'),
            array('e', array(), 'h')
        );

        $mock
            ->method('doSomething')
            ->will($this->returnValueMap($map));

        // $mock->doSomething() は、渡した引数に応じて異なる値を返します
        $this->assertEquals('d', $stub->doSomething('a'));
        $this->assertEquals('h', $stub->doSomething('e'));
    }
}

第二要素に謎の空配列、、
PHPUnit_Framework_MockObject_Stub_ReturnValueMapクラスのinvokeメソッドで
$invocation->parametersを覗いたら居いました。

バージョン古いからかな。。。
最新版では直ってるといいな。。。

11
12
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
11
12