PHPunit mocking在同一个模拟对象中调用mocked方法

时间:2013-09-09 11:24:28

标签: php unit-testing mocking dependencies phpunit

我对嘲笑对象有疑问......

我有“示例”类,我需要测试callMethod()

public function callMethod() {
  $item = 0;
  foreach($this->returnSomething() as $list) {
    $item = $item + $list->sum;
  }
  return $item; 
}

我有测试方法,我模拟“returnSomething”给我一些数据,但问题是它不会调用mocked方法。

这是测试方法的一部分,我嘲笑“returnSomething”并调用“callMethod”。

$mock = mock("Example");
$mock->shouldReceive("returnSomething")->once()->withNoArgs()->andReturn($returnItems);
$result = $mock->callMethod();

是否可以在不更改“callMethod”定义的情况下调用mocked“returnSomething”并将$ mock对象转发到该方法中?

2 个答案:

答案 0 :(得分:1)

可以仅模拟指定的方法。

<强>示例:

嘲笑:

$mock = \Mockery::mock("Example[returnSomething]");

PHPUnit的:

$mock = $this->getMock('Example', array('returnSomething'));

$mock = $this->getMockBuilder('Example')
    ->setMethods(array('returnSomething'))
    ->getMock();

在上述情况下,框架将仅模拟returnSomething方法,并将其余方法保留为原始对象。

答案 1 :(得分:0)

我之所以写这篇文章,是因为今天我在这里找到了答案,但是不赞成使用setMethods()(phpunit 8.5),替代方法是onlyMethods(),它可以如下使用:

$mock = $this->getMockBuilder(Example::class)
             ->onlyMethods(['yourOnlyMethodYouWantToMock'])
             ->getMock();

$mock->method('yourOnlyMethodYouWantToMock')
            ->withAnyParameters()
            ->willReturn($yourReturnValue);