【问题标题】:Mockery "with" method not showing why fails嘲弄“with”方法没有显示失败的原因
【发布时间】:2020-06-10 05:53:38
【问题描述】:

我在模拟上使用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 (
    ),
  ),
))

【问题讨论】:

    标签: php phpunit mockery


    【解决方案1】:

    当你将一个对象作为参数传递给方法时,在这种情况下你传递的是对象(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
    });
    

    也许这对你有帮助。

    【讨论】:

    • 感谢 mohammad,我也这样做,使用 clousures 专门比较字段。应该有办法直接比较它们,有时我可以完成但是当它们不同时也很难知道哪个字段不同
    猜你喜欢
    • 2017-09-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多