在 Laravel 中测试时如何模拟 time() 函数?

Ben*_*ict 2 php testing laravel laravel-testing

我正在使用 Laravel 做一个数学竞赛项目。项目中的所有控制器方法都使用了大量的 time() 函数。

根据当前时间是否在比赛直播时间之间向用户返回问题。

在编写功能测试和单元测试时,如何模仿控制器中的 time() 函数,以便在为项目运行测试时设置所需的时间?

Bed*_*ang 16

您可以通过两种方式与时间互动:

选项 1:使用 Laravel 内置函数

注意: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();
Run Code Online (Sandbox Code Playgroud)

参考:https: //laravel.com/docs/mocking#interacting-with-time

选项 2:碳法

Carbon::setTestNow();
Run Code Online (Sandbox Code Playgroud)

或设置任何日期

$knownDate = Carbon::create(2001, 5, 21, 12);
Carbon::setTestNow($knownDate); // Or any dates    
echo Carbon::now();  // will show 2001-05-21 12:00:00
Run Code Online (Sandbox Code Playgroud)

参考:https://laraveldaily.com/carbon-trick-set-now-time-to-whatever-you-want/