我正在使用 Laravel 做一个数学竞赛项目。项目中的所有控制器方法都使用了大量的 time() 函数。
根据当前时间是否在比赛直播时间之间,将问题返回给用户。
在编写功能测试和单元测试时,如何模拟控制器中的 time() 函数,以便在为项目运行测试时设置我想要的时间?
我正在使用 Laravel 做一个数学竞赛项目。项目中的所有控制器方法都使用了大量的 time() 函数。
根据当前时间是否在比赛直播时间之间,将问题返回给用户。
在编写功能测试和单元测试时,如何模拟控制器中的 time() 函数,以便在为项目运行测试时设置我想要的时间?
您可以通过两种方式与时间交互:
注意:Laravel 版本 >= 8
最新版本的 Laravel 有很好的与时间交互的方法:
$this->travel(5)->milliseconds();
$this->travel(5)->seconds();
$this->travel(5)->minutes();
$this->travel(5)->hours();
$this->travel(5)->days();
$this->travel(5)->weeks();
$this->travel(5)->years();
// Travel into the past...
$this->travel(-5)->hours();
// Travel to an explicit time...
$this->travelTo(now()->subHours(6));
// Return back to the present time...
$this->travelBack();
参考:https ://laravel.com/docs/mocking#interacting-with-time
Carbon::setTestNow();
或设置任何日期
$knownDate = Carbon::create(2001, 5, 21, 12);
Carbon::setTestNow($knownDate); // Or any dates
echo Carbon::now(); // will show 2001-05-21 12:00:00
参考:https ://laraveldaily.com/carbon-trick-set-now-time-to-whatever-you-want/
我认为应该使用 Carbon 而不是time()
:
Carbon::now()->timestamp // Or just now()->timestamp in 5.5+
您可以轻松地模拟 Carbon 实例。
如果你不使用time()
很多,你也可以创建自己的助手:
function timestamp()
{
if (app()->runningUnitTests()) {
return ....
} else {
return time();
}
}
并使用它代替time()
:
timestamp()