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

时间:2018-02-18 06:30:02

标签: php laravel testing laravel-testing

我正在使用Laravel进行数学竞赛项目。项目中的所有控制器方法都使用了很多time()函数。

根据当前时间是否在比赛现场时间之间,问题将返回给用户。

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

2 个答案:

答案 0 :(得分:2)

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

选项 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();

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

选项 2:碳法

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/

答案 1 :(得分:1)

我认为应该使用Carbon而不是time()

Carbon::now()->timestamp // Or just now()->timestamp in 5.5+

您可以轻松模拟Carbon实例。

如果你不经常使用time(),你也可以create your own helper

function timestamp()
{
    if (app()->runningUnitTests()) {
        return ....
    } else {
        return time();
    }
}

并使用它代替time()

timestamp()