php mock - > expected()在未调用

时间:2017-03-02 19:47:22

标签: php unit-testing mocking phpunit

我有以下模拟对象:

$permutator = $this->getMockBuilder('PermutationClass', 
array('get_permutation'))->disableOriginalConstructor()->getMock();

$permutator->expects($this->at(0))
                  ->method('get_permutation')
                  ->will($this->returnCallback(function($praram1) {
                        return true;
                  }));
$permutator->expects($this->at(1))
                  ->method('get_permutation')
                  ->will($this->returnCallback(function($praram1) {
                        return true;
                  }));

然而,我所经历的是,如果由于某种原因,在" 1"永远不会被执行,然后没有报告关于期望永远不会被满足的错误。

如果我添加以下代码:就在预期之前:

$permutator->expects($this->exactly(2))->method('get_permutation');

然后会发生的是,如果从未调用过给定的期望,则会报告错误。但是,这里发生的是由于某种原因,这使得模拟对象的返回值为NULL,因为我没有设置它。如果我这样设置:

$permutator->expects($this->exactly(2))->method('get_permutation')->will($this->returnValue("THIS SHOULD NEVER BE RETURNED"));

然后,这将成为该函数的所有预期方法调用的返回值。所以在(0)和(1)处执行(我设置了一些打印语句),但返回值被覆盖:

$permutator->expects($this->exactly(2))->method('get_permutation');

我设法使用以下方式获得预期的行为:

$permutator->expects($this->exactly(2))
           ->method('get_permutation')
           ->will( $this->onConsecutiveCalls(
                       $this->returnCallback(function($praram1) {
                           return true;
                       }),
                       $this->returnCallback(function($praram1) {
                           return false;
                       })
                   )
           );

我得到的是为什么模拟对象不会抱怨说,当我明确设定期望时,(1)中的$ this->从未被调用过?

1 个答案:

答案 0 :(得分:-1)

这不是expects所做的 - 它所做的就是告诉模拟在调用该函数时返回什么。 不是断言。

如果你想声明一个方法被调用,我会调查https://github.com/phpspec/prophecy#spies

或者,您可以使用returnCallback来保存调用哪些参数,然后将其与您应知的内容进行比较,如下所示:

$params = [];
$permutator->expects($this->any())
->method('get_permutation')
->will($this->returnCallback(
    function($param) use (&$params){
        $params[] = $param);
    }
));

doTheThing();

$this->assertEquals(
  array(1,2),
  $params
);