如何使用PHPUnit和mock对象测试是否使用正确的参数调用相同的方法

Fin*_*ino 9 php phpunit

我正在使用PHPUnit进行单元测试我使用模拟对象来测试是否使用正确的参数调用方法.当我只想这样做一次时,这很好用.

    $logMock = $this->getMockBuilder('Logger')
            ->disableOriginalConstructor()
            ->getMock();

    //check if it updates the correct record
    $logMock->expects($this->exactly(1))
            ->method('updateLog')
            ->with(456, 'some status');
Run Code Online (Sandbox Code Playgroud)

现在,我想测试是否第二次调用updateLog(使用不同的参数).我不知道如何用'with'方法做到这一点.

有人有建议吗?

tre*_*eze 15

我不知道你的嘲弄框架.通常你只是创造另一个期望.我认为这也应该适用于这个框架.

$logMock->expects($this->exactly(1))
         ->method('updateLog')
         ->with(100, 'something else');
Run Code Online (Sandbox Code Playgroud)

编辑

似乎PHPUnit框架不支持对同一方法的多个不同期望.根据此站点,您必须使用索引功能.

它会是这样的

$logMock->expects($this->at(0))
        ->method('updateLog')
        ->with(456, 'some status');
$logMock->expects($this->at(1))
         ->method('updateLog')
         ->with(100, 'something else');
$logMock->expects($this->exactly(2))
        ->method('updateLog');
Run Code Online (Sandbox Code Playgroud)


Set*_*ers 6

返回回调

如果您无法使用withConsecutive(),可能是因为您使用的是旧版本的 PHPUnit,那么您还有另一个选择returnCallback

returnCallback每次调用模拟方法时都会调用该函数。这意味着您可以保存传递给它的参数以供以后检查。例如:

$actualArgs = array();

$mockDependency->expects($this->any())
    ->method('setOption')
    ->will($this->returnCallback(
        function($option, $value) use (&$actualArgs){
            $actualArgs[] = array($option, $value);
        }
    ));

$serviceUnderTest->executeMethodUnderTest();

$this->assertEquals(
    array(
        array('first arg of first call', 'second arg of first call'),
        array('first arg of second call', 'second arg of second call'),
    ),
    $actualArgs);
Run Code Online (Sandbox Code Playgroud)