【问题标题】:PHP Unit Testing: How can we pass multiple parameters while mocking a method?PHP 单元测试:我们如何在模拟方法时传递多个参数?
【发布时间】:2016-11-08 11:56:20
【问题描述】:
    $observer = $this->getMockBuilder('Apps_Sample_DataHandler')
            ->disableOriginalConstructor()
            ->disableOriginalClone()
            ->disableArgumentCloning()
            ->getMock();

    $observer->method('getSampleData')
         ->will($this->returnCallback('mockTestCall'));


    $this->assertEquals('foo', $observer->getSampleData());

这里我们尝试用“mockTestCall”模拟方法“getSampleData”。

我们想知道如何将参数传递给方法“mockTestCall”。

“mockTestCall”方法的定义如下:

public function mockTestCall($arg1){
    return $arg1;
}

【问题讨论】:

    标签: php unit-testing


    【解决方案1】:

    对于 PHP >= 5.4:

    $observer->method('getSampleData')
        ->will($this->returnCallback(
            function() {
                $this->mockTestCall('arg1_value');
            }
        ));
    

    对于 PHP 5.3:

    $that = $this;
    $observer->method('getSampleData')
        ->will($this->returnCallback(
            function() use($that) {
                $that->mockTestCall('arg1_value');
            }
        ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 2015-10-21
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多