phpunit 可以比较两个不同的对象并断言它们的属性相同吗?

Can phpunit compare two different objects asserting that their properties are identical?

提问人:Leo Galleguillos 提问时间:2/25/2020 最后编辑:Leo Galleguillos 更新时间:2/25/2020 访问量:4248

问:

下面的测试通过了,因为 ,但我想写一个失败的测试,因为 。true == 1true !== 1

$stdClass1 = new stdClass();
$stdClass1->foo = true;
$stdClass2 = new stdClass();
$stdClass2->foo = 1;

$this->assertEquals(
    $stdClass1,
    $stdClass2
);

以下测试失败,因为这两个变量不引用同一个对象,但我想编写一个通过的测试,因为 .true === true

$stdClass1 = new stdClass();
$stdClass1->foo = true;
$stdClass2 = new stdClass();
$stdClass2->foo = true;

$this->assertSame(
    $stdClass1,
    $stdClass2
);

因此,phpunit 是否提供了一种原生方法来比较两个不同的对象,并断言它们的属性是相同的?

我见过将对象转换为数组然后使用 ,或序列化对象然后使用 ,等等的解决方案(hacks)。但是,对于具有由几种不同数据类型组成的属性的大型对象,这些解决方案并不理想。分别,在尝试将数据类型(如 DateTime 转换为浮点数)时,规范化失败,或者序列化后生成的错误消息长达数百行,因此查找差异很繁琐。$this->assertEqualsCanonicalizing()this->assertEquals()

因此,phpunit 是否提供了一种原生方法来比较两个不同的对象,并断言它们的属性是相同的?

目前,我们唯一可靠的解决方案是为每个属性编写一个特定的测试。也许 phpunit 的这个决定是故意的,以便强制进行更健壮的单元测试。

$this->assertSame(
    $stdClass1->foo,
    $stdClass2->foo
);

为了比较对象,上面的测试可以按预期工作,尽管我们需要遍历所有属性和每个属性。assertSame

单元测试 对象 phpunit 比较器

评论

2赞 Don't Panic 2/25/2020
根据文档,看起来它适用于对象,而无需事先将它们转换为数组,尽管它确实在内部将它们转换为数组。assertEqualsCanonicalizing()
0赞 Mohammad.Kaab 4/13/2020
我总是在比较对象时遇到同样的问题,我通常会一个一个地比较对象属性,但我没有任何具有大量属性的大对象可以比较。

答: 暂无答案