【问题标题】:CakePHP 3: Set current time for unit testingCakePHP 3:为单元测试设置当前时间
【发布时间】:2015-12-30 17:01:47
【问题描述】:

在 CakePHP 3 中,我使用内置类 Cake\I18n\Time 来计算 API 响应和当前时间的时间差。结果正在存储以进行单元测试,但我不知道如何设置当前时间,因此预期结果会不断变化。

这是我要测试的单元:

$apiTime = Time::createFromTimestamp($apiTimestamp);

// Get the time the prediction was generated
$currentTime = Time::now();

return (int)(($apiTime->getTimestamp() - $currentTime->getTimestamp()) / 60);

那么,有什么方法可以设置当前时间吗?这样我就可以真正知道预期的结果是什么。

【问题讨论】:

    标签: unit-testing cakephp cakephp-3.0


    【解决方案1】:

    (来自http://book.cakephp.org/3.0/en/core-libraries/time.html#creating-time-instances)

    在测试用例中,您可以使用 setTestNow() 模拟 now():

    // Fixate time.
    $now = new Time('2014-04-12 12:22:30');
    Time::setTestNow($now);
    
    // Returns '2014-04-12 12:22:30'
    $now = Time::now();
    
    // Returns '2014-04-12 12:22:30'
    $now = Time::parse('now');
    

    【讨论】:

    猜你喜欢
    • 2017-08-24
    • 2016-06-04
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2023-04-04
    • 2010-10-17
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多