dtvam48220 2017-01-01 03:00
浏览 53

PHPUnit,测试使用根据当前时间设置的类字段的方法

I'm building a little Timer class that has a start() and stop() method, each of these will set a Carbon object with the current timestamp, then i have the method i'm trying to test, this method will calculate the difference between timestamps to get the total number of seconds elapsed in the Timer.

I'm having a problem unit testing this method, because it depends on the current timestamp, i don't think putting a sleep(1) in the test is a good idea, so, my question is, is there any way i can make the method use two other specific Carbon instances while it's running?

This is my method as it stands, it uses the two protected fields endTime and startTime from it's class.

/**
 * Get the total elapsed time as the difference in seconds
 * between startTime and endTime
 *
 * @return int Number of seconds elapsed
 */
public function getElapsedTime()
{
    if(!$this->endTime)
        return $this->startTime->diffInSeconds(Carbon::now('Europe/Lisbon'));

    return $this->startTime->diffInSeconds($this->endTime);
}
  • 写回答

1条回答 默认 最新

  • dongyi6183 2017-01-01 03:15
    关注

    I did it by using Reflection

    /**
     * The elapsedTime method should return a string
     * if both startTime and endTime are defined
     */
    public function testElapsedTimeMethod()
    {
        $reflection = new \ReflectionClass($this->timer);
        $startTime  = $reflection->getProperty('startTime');
        $endTime    = $reflection->getProperty('endTime');
    
        $startTime->setAccessible(true);
        $endTime->setAccessible(true);
    
        $startTime->setValue($this->timer, Carbon::createFromTimestamp(1483240345));
        $endTime->setValue($this->timer, Carbon::createFromTimestamp(1483240348));
    
        $secondsElapsed = $this->timer->getElapsedTime();
    
        $this->assertEquals(3, $secondsElapsed);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度