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.

  • 写回答

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'); }
            ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 arcgis中更新地理配准后几个图层分离怎么解决?
  • ¥15 想请教大家关于机器学习的问题
  • ¥15 虚幻UE保存Actor位置失败
  • ¥15 多个.nii合并为.nii.gz格式
  • ¥50 现在需要统计2023年全年 “签收时间(qssj)” 到 “提交时间(tjsj)” 小于半小时的业务量,但是要排除掉周末的时间,同时还要排除中午休息的时间。
  • ¥50 opencv模板匹配为何图像差别大仍然匹配数值高?
  • ¥15 如何成功完成主菜单和分菜单的代码编程C++
  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?