Gor*_*don 20
您应该DateTime在测试中存储所需的方法以返回预期值.
$stub = $this->getMock('DateTime');
$stub->expects($this->any())
->method('theMethodYouNeedToReturnACertainValue')
->will($this->returnValue('your certain value'));
Run Code Online (Sandbox Code Playgroud)
请参阅https://phpunit.de/manual/current/en/test-doubles.html
如果您不能将方法存根,因为它们已经硬编码到您的代码中,请查看
这解释了如何在调用时new调用回调.然后,您可以使用具有固定时间的自定义DateTime类替换DateTime类.另一种选择是使用http://antecedent.github.io/patchwork
你也可以使用时间旅行者lib,它使用aop php pecl扩展来带来类似于ruby monkey patching的东西https://github.com/rezzza/TimeTraveler
还有这个php扩展,灵感来自ruby timecop one:https: //github.com/hnw/php-timecop