使用PHPUnit Mock在returnValue中克隆对象

时间:2014-04-23 10:48:54

标签: php phpunit

我正在嘲笑一个看起来像这样的类的方法:

class Employee { 

/**
 * @return \DateTime
 */
public function getEmploymentBegin()
{
    return clone $this->employmentBegin;
}

我的模拟看起来像:

$employee = $this->getMockBuilder('\MyApp\Employee')->disableOriginalConstructor()->getMock();

$employee
        ->expects($this->any())
        ->method('getEmploymentBegin')
        ->will($this->returnValue(date_create('05.11.2012')));

后来我测试的代码需要操作日期:

$a= $this->employee->getEmploymentBegin();
$b = $this->employee->getEmploymentBegin();
$b->modify('+ 6 weeks')->modify('yesterday');

我的问题最后$a$b结尾使用相同的引用。

2 个答案:

答案 0 :(得分:0)

您可以将模拟更改为:

$date = date_create('05.11.2012');
$employee
    ->expects($this->any())
    ->method('getEmploymentBegin')
    ->will($this->onConsecutiveCalls(clone $date, clone $date));

clone似乎是一个重要的实施细节。我不知道该怎么处理。也许getEmploymentBegin应该返回一个简单类型(如字符串)。任何想要进行日期算术的东西都可以将其升级为Date

答案 1 :(得分:0)

看起来好像使用returnCallback()完成了这项工作。

    $employee
        ->expects($this->any())
        ->method('getEmploymentBegin')
        ->will($this->returnCallback(
            function () { return date_create('05.11.2012'); }
        ));
相关问题