首页 文章

PHPUnit:如何使用多个参数模拟多个方法调用?

提问于
浏览
45

我正在为使用PHPUnit的方法编写单元测试 . 我正在测试的方法在同一个对象上调用同一个方法3次,但使用不同的参数集 . 我的问题类似于问题herehere

其他帖子中提出的问题与只采用一个论点的模拟方法有关 .

但是,我的方法需要多个参数,我需要这样的东西:

$mock->expects($this->exactly(3))
     ->method('MyMockedMethod')
     ->with($this->logicalOr($this->equalTo($arg1, $arg2, arg3....argNb),
                             $this->equalTo($arg1b, $arg2b, arg3b....argNb),
                             $this->equalTo($arg1c, $arg2c, arg3c....argNc)
         ))

此代码不起作用,因为 equalTo() 仅验证一个参数 . 给它多个参数会引发异常:

PHPUnit_Framework_Constraint_IsEqual :: __ construct()的参数#2必须是数字

有没有办法对具有多个参数的方法进行 logicalOr 模拟?

提前致谢 .

4 回答

  • 8

    在我的情况下,答案变得非常简单:

    $this->expects($this->at(0))
        ->method('write')
        ->with(/* first set of params */);
    
    $this->expects($this->at(1))
        ->method('write')
        ->with(/* second set of params */);
    

    关键是使用 $this->at(n)n 是方法的第N个调用 . 我试过的任何 logicalOr() 变种都无法做任何事情 .

  • 24

    Stubbing a method call to return the value from a map

    $map = array(
        array('arg1_1', 'arg2_1', 'arg3_1', 'return_1'),
        array('arg1_2', 'arg2_2', 'arg3_2', 'return_2'),
        array('arg1_3', 'arg2_3', 'arg3_3', 'return_3'),
    );
    $mock->expects($this->exactly(3))
        ->method('MyMockedMethod')
        ->will($this->returnValueMap($map));
    

    或者你可以使用

    $mock->expects($this->exactly(3))
        ->method('MyMockedMethod')
        ->will($this->onConsecutiveCalls('return_1', 'return_2', 'return_3'));
    

    如果您不需要指定输入参数

  • 24

    对于那些希望匹配输入参数并为多个调用提供返回值的人来说......这对我有用:

    $mock->method('myMockedMethod')
             ->withConsecutive([$argA1, $argA2], [$argB1, $argB2], [$argC1, $argC2])
             ->willReturnOnConsecutiveCalls($retValue1, $retValue2, $retValue3);
    
  • 67

    如果有人在没有查看phpunit文档中的correspondent section的情况下找到这个,你可以使用 withConsecutive 方法

    $mock->expects($this->exactly(3))
         ->method('MyMockedMethod')
         ->withConsecutive(
             [$arg1, $arg2, $arg3....$argNb],
             [arg1b, $arg2b, $arg3b....$argNb],
             [$arg1c, $arg2c, $arg3c....$argNc]
             ...
         );
    

    唯一的缺点是代码必须按照提供的参数顺序调用 MyMockedMethod . 我还没有找到办法解决这个问题 .

相关问题