【问题标题】:PHPunit mocking call mocked method in same mocked objectPHPunit模拟在同一个模拟对象中调用模拟方法
【发布时间】:2013-09-12 21:04:33
【问题描述】:

我对模拟对象有疑问...

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

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

我有一个测试方法,我模拟“returnSomething”来返回一些数据,但问题是它没有调用模拟方法。

这是我模拟“returnSomething”并调用“callMethod”的测试方法的一部分。

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

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

【问题讨论】:

    标签: php unit-testing mocking dependencies phpunit


    【解决方案1】:

    可以只模拟指定的方法。

    示例:

    嘲讽:

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

    PHPUnit:

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

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

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

    【讨论】:

    • 我相信 PHPUnit 允许您通过不设置数组('returnSomething')来模拟所有函数,但将其留空以模拟所有函数。但是,您只会收到一个返回值。
    • 我以这种方式理解了这个问题:如何仅模拟类中的某些方法,并将其余方法保留在原始类中。我看到我的表达“你可以只模拟指定的方法”令人困惑,我的意思是:“可以只模拟指定的方法”。我会修复答案,谢谢
    • 谨慎使用setMethods()。此方法自 PHPUnit 8 起已弃用,将在 PHPUnit 10 中删除。请改用onlyMethods()。可以在此处的答案中找到一个示例。
    【解决方案2】:

    我写这个是因为今天我在这里找到了答案,但是 setMethods() 已被弃用(phpunit 8.5),替代方案是 onlyMethods(),它可以如下使用:

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

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 2017-08-25
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      相关资源
      最近更新 更多