PHPUnit 等于在具有 delta 的日期上

2022-08-30 13:56:17

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

答案 1

增量值只需要是秒数

您需要的秒数,时间戳可以不同于 或 在您的情况下.这两个函数( assertEquals / equalTo ) 都指向,因此 delta 处理是相同的。4th parameter to assert equals2nd to equalToPHPUnit_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

答案 2

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


推荐