14

This following test passes because true == 1, but I would like to write a test that fails since true !== 1.

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

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

The following test fails because the two variables do not reference the same object, but I would like to write a test that passes since true === true.

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

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

Therefore, does phpunit offer a native way to compare two different objects asserting that their properties are identical?

I have seen solutions (hacks) which convert the objects into arrays in then use $this->assertEqualsCanonicalizing(), or serialize the objects and then use this->assertEquals(), and so on. However, these solutions are not ideal for large objects which have properties consisting of a few different data types. Respectively, the canonicalization fails when attempting to convert a data type (such as DateTime to float), or the error message produced after serialization is hundreds of lines long making it tedious to find one difference.

Therefore, does phpunit offer a native way to compare two different objects asserting that their properties are identical?

For now, the only reliable solution we have is to write a specific test for each property. Perhaps this decision by phpunit is deliberate in order to force more robust unit tests.

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

The above test works as desired for the purpose of comparing objects, although we will need to loop through all of our properties and assertSame for each one.

2
  • 2
    According to the documentation, assertEqualsCanonicalizing() looks like it works on objects without converting them to arrays beforehand, though it does convert them to arrays internally. Commented Feb 24, 2020 at 22:27
  • I've always had the same problem of comparing objects, I usually compare the object properties one by one, but I didn't have any big object with tons of properties to compare. Commented Apr 13, 2020 at 1:07

0