How can I write a unittest in this particular scenario? Or is this a bad question?
I have two date variables as shown below:
$startDate = new \DateTime('2013-01-01');
$endDate = new \DateTime()->format(\DateTime::ISO8601);
If I count the difference between the two dates, the result will be different on each test run. Thus, I cannot use any constant number to assert that the difference is correct, but my test is to make sure that at any given time the difference between the two dates is perfect!
How can I achieve this? Any comments or suggestions would be really helpful! Hooray!
+3
Sharif mamun
source
to share
1 answer
To allow your test to be independent of the system clock or whatever, you can do something like this: Suppose you have a simple function that calculates the age in year, you can add a second argument to your function. so that the current date, if not set, defaults to:
// DateRangeUtil
public static function getYearAge($registrationDate,$now = null)
{
if (!$now)
{
$now = new \DateTime('now');
}
return $now->diff($registrationDate)->format("%y");
}
// DateRangeUtilTest
public function testGetYearAge()
{
$bornDate = \Datetime::createFromFormat("d/m/Y H:i:s", "01/03/2014 00:00:00");
$today = \Datetime::createFromFormat("d/m/Y H:i:s", "01/06/2015 00:00:00");
$this->assertEquals(1, DateRangeUtil::getYearAge($bornDate, $today)," expect one year old");
}
Hope for this help
+3
Matteo
source
to share