模拟所有DateTime实例用于测试目的的时间

Ben*_*ine 20 php testing datetime phpunit behat

我希望能够在DateTimePHPUnit或Behat Test的持续时间内为每个实例化实例设置时间.

我正在测试与时间相关的业务逻辑.例如,类中的方法仅返回过去或将来的事件.

如果可能的话,我不想这样做:

  1. 写一个包装器DateTime并使用它代替DateTime整个代码.这将涉及重写我当前的代码库.

  2. 每次运行测试/套件时动态生成数据集.

所以问题是:是否有可能覆盖DateTimes行为以始终在请求时提供特定时间?

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


sho*_*uze 8

你也可以使用时间旅行者lib,它使用aop php pecl扩展来带来类似于ruby monkey patching的东西https://github.com/rezzza/TimeTraveler

还有这个php扩展,灵感来自ruby timecop one:https: //github.com/hnw/php-timecop