Search code examples
phpphpunitmockery

Mockery "with" method not showing why fails


I'm using with method on a mock in order to assert that the method is called with an object as an argument

        Mockery::mock(PaymentRepository::class)
             ->shouldReceive('removeTripPayments')
             ->with($trip)
             ->mock();

Which fails, I still don't know why, but I'm mostly concerned about if this is the correct way to check it and if it is possible to show how the expected argument is different from the given one.

1) PaymentServiceTest::test_removing_payments
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_PaymentRepository::removeTripPayments(object(Trip)). Either the method was unexpected or its arguments matched no expected argument list for this method

Objects: ( array (
  'MyNamespace\Trip' =>
  array (
    'class' => 'MyNamespace\\Trip',
    'properties' =>
    array (
    ),
  ),
))

Solution

  • When you are passing an object to the method as an argument, Which in this case you are passing object(Trip), Then PHPUnit getting crazy. I have always had this problem and you have two solutions for it, the first one using Mockery::on();

    ->with(Mockery::on(function($Param){
        $this->assertEqual(get_class($Param), get_class(Trip));
        return true;
    }))
    

    As you can see PHPUnit can't compare the two objects completely, so you need to compare part of the objects, which in this case I have used get_clas to check the name of the classes. And the second solution could be using

    ->andReturnUsing(function($param){
       $this->assertEqual(get_class($Param), get_class(Trip));
       return true; // Expected response
    });
    

    Maybe this can be helpful to you.