Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHPUnit:期望方法含义_Php_Unit Testing_Tdd_Mocking_Phpunit - Fatal编程技术网

PHPUnit:期望方法含义

PHPUnit:期望方法含义,php,unit-testing,tdd,mocking,phpunit,Php,Unit Testing,Tdd,Mocking,Phpunit,当我创建一个新的mock时,我需要调用expects方法。它到底是干什么的?它的论点如何 $todoListMock = $this->getMock('\Model\Todo_List'); $todoListMock->expects($this->any()) ->method('getItems') ->will($this->returnValue(array($itemMock)));

当我创建一个新的mock时,我需要调用expects方法。它到底是干什么的?它的论点如何

$todoListMock = $this->getMock('\Model\Todo_List');
        $todoListMock->expects($this->any())
            ->method('getItems')
            ->will($this->returnValue(array($itemMock)));

我到处都找不到原因(我试过文档)。我已经阅读了源代码,但无法理解。

查看源代码会告诉您:

/**
 * Registers a new expectation in the mock object and returns the match
 * object which can be infused with further details.
 *
 * @param  PHPUnit_Framework_MockObject_Matcher_Invocation $matcher
 * @return PHPUnit_Framework_MockObject_Builder_InvocationMocker
 */
public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher);
PHPUnit手册列出了以下可用的匹配器:

  • any()返回一个匹配器,该匹配器在对其求值的方法执行零次或多次时匹配
  • never()返回一个匹配器,该匹配器在为其求值的方法从未执行时匹配
  • atLeastOnce()返回一个匹配器,该匹配器在对其求值的方法至少执行一次时匹配
  • once()返回一个匹配器,该匹配器在为其求值的方法只执行一次时匹配
  • 精确(int$count)返回一个匹配器,该匹配器在为其求值的方法精确执行$count次时匹配
  • at(int$index)返回一个匹配器,该匹配器在给定的$index处调用其求值的方法时匹配
expects()-设置希望调用方法的次数:

如果您知道,在expects()中调用该方法一次使用$this->once(),否则使用$this->any()

请参阅:


如果调用一次,然后再次调用,会发生什么?如果预期调用一次的方法将被调用更多次,测试可能会失败!你做得很好!每个->will()的末尾都有一个(缺少)和一个。我想知道方法expects()背后的原因。我所能看到的是,如果我给出any()的参数,它将起作用。在模拟对象时,似乎不需要此方法。我需要进一步了解这个问题。我知道这一定是有原因的。请注意at()从0开始。我今天通过一些尝试和错误发现了这一点。还要注意,
at()
对模拟对象上的所有存根方法使用相同的计数器。它不会为每个方法分配新的计数器。
$mock = $this->getMock('nameOfTheClass', array('firstMethod','secondMethod','thirdMethod'));
$mock->expects($this->once())
     ->method('firstMethod')
     ->will($this->returnValue('value'));
$mock->expects($this->once())
     ->method('secondMethod')
     ->will($this->returnValue('value'));
$mock->expects($this->once())
     ->method('thirdMethod')
     ->will($this->returnValue('value'));