PHPUnit等于带有delta的日期

时间:2011-08-17 10:35:38

标签: php phpunit

我在PHPUnit中遇到问题,我想在比较日期时在equalTo方法中使用delta参数。 假设我想将日期视为相等,如果它们的差异不超过10秒。 $ some_delta的适当价值是多少? 10? 10000?或者完全不同的东西?

$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']));

3 个答案:

答案 0 :(得分:41)

delta值只需要是秒数

您需要时间戳可以与4th parameter to assert equals2nd to equalTo的情况不同的秒数。这两个函数(assertEquals / equalTo)都指向PHPUnit_Framework_Constraint_IsEqual,因此增量处理是相同的。

示例:

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

}

和输出

第一次测试工作第二次失败。

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

答案 1 :(得分:3)

爱琴海答案的补充-自PhpUnit v7.5起,您可以使用assertEqualsWithDelta()assertEquals()自PhpUnit v8起已弃用

答案 2 :(得分:1)

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(碳)

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

说明:自PHPUnit 8起,不推荐使用带有4个参数的assertEquals