2017-01-01 17 views
0

我建立具有start()stop()方法有點Timer類設置的方法,每一個這些將設置一個對象與當前時間戳,然後我有我正在嘗試測試的方法,此方法將計算時間戳之間的差異以獲取計時器中經過的總秒數。PHPUnit的,測試使用類字段根據當前時間

我有一個問題單元測試此方法,因爲它取決於當前的時間戳,我不認爲把sleep(1)在測試中是一個好主意,所以,我的問題是,有沒有什麼辦法可以讓該方法在運行時使用另外兩個特定的Carbon實例嗎?

這是我的方法,它使用兩個保護字段endTimestartTime從它的類。

/** 
* 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); 
} 

回答

0

我做到了通過使用反射

/** 
* 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); 
} 
相關問題