dsjj15012
2014-04-23 10:48
浏览 107
已采纳

使用PHPUnit Mock在returnValue中克隆对象

I am mocking a method from a class that looks like this:

class Employee { 

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

My mock looks like:

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

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

Later the code that I am testing needs to manipulate the date:

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

My issue is that at the end Both $a and $b end-up with the same reference.

图片转代码服务由CSDN问答提供 功能建议

我正在从类看起来像这样的方法:

   class Employee {
 
 / ** 
 * @return \ DateTime 
 * / 
 
共享函数getEmploymentBegin()
 {
返回clone $ this-> employmentBegin; 
} 
 <  / code>  
 
 

我的模拟看起来像:

  $ employee = $ this-&gt; getMockBuilder('\ MyApp \ Employee')  - &gt; disableOriginalConstructor() - &gt; getMock(); 
 
 $ employee 
  - &gt;期望($ this-&gt; any())
  - &gt;方法('getEmploymentBegin')
  - &gt  ; will($ this-&gt; returnValue(date_create('05 .11.2012'))); 
   
 
 

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

  $ a = $ this-&gt; employee-&gt; getEmploymentBegin(); 
 $ b = $ this-&gt; employee-&gt; getEmploymentBegin(); \  n $ b-&gt;修改('+ 6周') - &gt;修改('昨天'); 
   
 
 

我的问题是最后两个 $ a $ b 以相同的引用结束。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfei8399 2014-04-23 11:24
    已采纳

    It looks like using returnCallback() did the job.

        $employee
            ->expects($this->any())
            ->method('getEmploymentBegin')
            ->will($this->returnCallback(
                function () { return date_create('05.11.2012'); }
            ));
    
    点赞 打赏 评论
  • dqeznd1697 2014-04-23 11:10

    You can change your mock to:

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

    The clone seems like an important implementation detail. I'm not sure how to deal with that. Maybe getEmploymentBegin should return a simple type (like a string). Anything that wants to do date arithmetic can then upgrade it to a Date.

    点赞 打赏 评论

相关推荐 更多相似问题