【问题标题】:How to mock interface properly in Mockery?如何在 Mockery 中正确模拟界面?
【发布时间】:2019-10-09 00:20:07
【问题描述】:

对于单元测试,我通过以下方式创建了一个模拟对象:

$passenger = M::mock(PassengerInterface::class);

我将此模拟传递给我想要进行单元测试的服务。该服务正在尝试访问未定义的方法,因此通过以下方式按预期失败:

[BadMethodCallException] Method Mockery_3_Dreamlines_BookingService_Bundle_Bundle_Entity_PassengerInterface::isInfant() does not exist on this mock object  

我由此在模拟对象上定义了方法

$passenger = M::mock(PassengerInterface::class)->shouldReceive('isInfant')->andReturn(false);

然而,这意外地通过以下方式失败了测试:

[PHPUnit_Framework_Exception] Argument 2 passed to Dreamlines\BookingService\Bundle\Bundle\Operator\ResponseModifier\InfantPriceModifier::adjustPrice()
must implement interface Dreamlines\BookingService\OperatorBundle\Entity\PassengerInterface,
Mockery\CompositeExpectation given 

我做错了什么?

【问题讨论】:

    标签: php unit-testing mockery


    【解决方案1】:

    您使用的流利语法不正确。

    Mockery 的andReturn 不返回模拟对象,而是期望。您应该创建一个实例,对其进行变异,然后使用修改后的实例:

    $passenger = M::mock(PassengerInterface::class); // creates the mock
    $passenger->shouldReceive("isInfant")->andReturn(false); // this returns an expectation, let's ignore that return value
    // now you can use $passenger as expected
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 1970-01-01
      • 2018-09-13
      • 2020-05-10
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 2015-08-15
      • 2013-07-29
      相关资源
      最近更新 更多