嘲笑 "with" 方法未显示失败原因

Mockery "with" method not showing why fails

我在 mock 上使用 with 方法,以断言该方法是使用对象作为参数调用的

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

失败了,我仍然不知道为什么,但我最关心的是这是否是检查它的正确方法以及是否可以显示 如何预期参数与给定参数不同。

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 (
    ),
  ),
))

当您将对象作为参数传递给方法时,在本例中您传递的是对象 (Trip),然后 PHPUnit 变得疯狂。我一直遇到这个问题,你有两个解决方案,第一个使用 Mockery::on();

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

如您所见,PHPUnit 无法完全比较两个对象,因此您需要比较部分对象,在本例中我使用 get_clas 检查 类.第二种解决方案可以使用

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

也许这对你有帮助。