Search code examples
phpunitspy

Strictly spy method argument in PHPUnit


I have this spy in a test:
$subject->expects( $this->once() )->method( 'send_json_success' )->with( $expected );

$expected is an array and one of the items of this array should be set to 0.

Instead is currently set to an empty string, which is the source of the problem I'm fixing. I want to make sure the test fails when the item is set to an empty string, but I can't find how to tell PHPUnit to strictly check the array is exactly the same as $expected.

I can't use $this->same() because the method does not return anything: I need to test the method is called with the right arguments, instead.


Solution

  • As explained in the API documentation of the with() method, you can use a PHPUnit_Framework_Constraint object.

    A PHPUnit_Framework_Constraint_IsIdentical object is used to implement the TestCase::assetSame() method.

    So, it should be:

    <?php
    
    use PHPUnit_Framework_Constraint_IsIdentical;
    
    // Test case class...
    
    $subject->expects($this->once())
            ->method('send_json_success')
            ->with(new PHPUnit_Framework_Constraint_IsIdentical($expected));