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