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

Leo*_*los 12 phpunit unit-testing object comparator

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

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

$this->assertEquals(
    $stdClass1,
    $stdClass2
);
Run Code Online (Sandbox Code Playgroud)

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

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

$this->assertSame(
    $stdClass1,
    $stdClass2
);
Run Code Online (Sandbox Code Playgroud)

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

我见过一些解决方案(黑客),它们将对象转换为数组然后使用$this->assertEqualsCanonicalizing(),或者序列化对象然后使用this->assertEquals(),等等。然而,这些解决方案对于具有由几种不同数据类型组成的属性的大型对象来说并不理想。分别是,当尝试转换数据类型(例如 DateTime 到 float)时,规范化会失败,或者序列化后产生的错误消息长达数百行,使得查找差异变得很乏味。

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

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

$this->assertSame(
    $stdClass1->foo,
    $stdClass2->foo
);
Run Code Online (Sandbox Code Playgroud)

尽管我们需要循环遍历所有属性并assertSame针对每个属性,但上述测试可以按需要进行比较对象的目的。