Difference between assertEquals and assertSame in PHPUnit?

后端 未结 7 1149
别那么骄傲
别那么骄傲 2021-01-30 18:54

PHPUnit contains an assertEquals() method, but it also has an assertSame() one. At first glance it looks like they do the same thing.

What is the difference between the t

7条回答
  •  孤街浪徒
    2021-01-30 19:53

    When it comes to objects comparison:

    assertSame

    Can only assert if two objects are referencing the same object instance. So even if two separate objects have for all of their attributes exactly the same values, assertSame() will fail if they don't reference the same instance.

    $expected = new \stdClass();
    $expected->foo = 'foo';
    $expected->bar = 'bar';
    
    $actual = new \stdClass();
    $actual->foo = 'foo';
    $actual->bar = 'bar';
    
    $this->assertSame($expected, $actual); // FAILS
    

    assertEquals

    Can assert if two separate objects match their attribute values in any case. So it's the method suitable for asserting object match.

    $this->assertEquals($expected, $actual); // PASSES
    

    Reference

提交回复
热议问题