PHPUnit equalTo on dates with delta
PHPUnit >= 7.5 (DateTime)
class MyDatesTest extends PHPUnit_Framework_TestCase {
public function testAllDateOk() {
$date1 = new DateTime('2019-01-01 00:00:00');
$date2 = new DateTime('2019-01-01 00:00:03');
// ± 5 seconds are equals
$this->assertEqualsWithDelta($date1->getTimestamp(), $date2->getTimestamp(), 5);
// ± 1 second are distinct
$this->assertNotEqualsWithDelta($date1->getTimestamp(), $date2->getTimestamp(), 1);
}
}
PHPUnit >= 7.5 (Carbon)
class MyDatesTest extends PHPUnit_Framework_TestCase {
public function testAllDateOk() {
$date1 = Carbon::now();
$date2 = Carbon::now()->addSeconds(3);
// ± 5 seconds are equals
$this->assertEqualsWithDelta($date1->timestamp, $date2->timestamp, 5);
// ± 1 second are distinct
$this->assertNotEqualsWithDelta($date1->timestamp, $date2->timestamp, 1);
}
}
Explanation: assertEquals with 4 params is deprecated since PHPUnit 8
The delta values just needs to be the number of seconds
You need the seconds the timestamps can differ as the 4th parameter to assert equals
or in your case the 2nd to equalTo
. Both of those functions ( assertEquals
/ equalTo
) point to PHPUnit_Framework_Constraint_IsEqual
so the delta handling is the same.
Sample:
<?php
class foo extends PHPUnit_Framework_TestCase {
public function testDateDiffsWorks() {
$date1 = new DateTime('2011-01-01 00:00:00');
$date2 = new DateTime('2011-01-01 00:00:03');
$this->assertEquals($date1->getTimestamp(), $date2->getTimestamp(), '', 5);
}
public function testDateDiffsFails() {
$date1 = new DateTime('2011-01-01 00:00:00');
$date2 = new DateTime('2011-01-01 00:00:03');
$this->assertEquals($date1->getTimestamp(), $date2->getTimestamp(), '', 0.5);
}
}
And the output
The first test works the second fails.
phpunit test.php
PHPUnit 3.5.14 by Sebastian Bergmann.
.F
Time: 0 seconds, Memory: 6.00Mb
There was 1 failure:
1) foo::testDateDiffsFails
Failed asserting that <integer:1293836403> matches expected <integer:1293836400>.
/home/edo/test.php:16
Addition to edorian answer - since PhpUnit v7.5 you can use assertEqualsWithDelta()
, assertEquals()
is deprecated since PhpUnit v8