Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit equalTo on dates with delta

Tags:

php

phpunit

I've got a problem in PHPUnit where I would like to use delta parameter in equalTo method when comparing dates. Let say I want to treat dates as equal if they differ in no more than 10 seconds. What would be appropriate value of $some_delta? 10? 10000? Or something totally different?

$this->_restClient->expects($this->at(0))     ->method('getData')     ->with(         $this->equalTo(array('1')),         $this->equalTo(array('2')),         $this->equalTo($this->_date, $some_delta),         $this->equalTo(null),     )     ->will($this->returnValue($this->_restResponses['generalRestResponse'])); 
like image 967
P. Šileikis Avatar asked Aug 17 '11 10:08

P. Šileikis


1 Answers

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 
like image 97
edorian Avatar answered Sep 28 '22 11:09

edorian