【问题标题】:Why does Mockery return demeter_getMyClass instead of MyClass?为什么 Mockery 返回 demeter_getMyClass 而不是 MyClass?
【发布时间】:2017-06-30 13:50:23
【问题描述】:

我尝试模拟多个方法调用。如in the documentation 所述,测试以下方法调用:

$object->foo()->bar()->zebra()->alpha()->selfDestruct();

我们可以使用下面这段代码:

$mock = \Mockery::mock('CaptainsConsole');
$mock->shouldReceive('foo->bar->zebra->alpha->selfDestruct')->andReturn('Ten!');

所以,我实现了它:

public function testProcessPayment()
{
    $offerPayment =  m::mock('MyApp\Model\Entity\OfferPayment');

    $paymentTransaction = m::mock('MyApp\Model\Entity\PaymentTransaction');
    $paymentTransaction->shouldReceive('getOfferPayment->getOffer')->andReturn($offerPayment);

    $transactionManager = new TransactionManager();
    $transactionManager->processPayment($paymentTransaction);

    $this->assertInstanceOf('Offer', $paymentTransaction->getOfferPayment()->getOffer());
}

相关类:

class TransactionManager
{
    public function processPayment(PaymentTransaction $paymentTransaction) {
        $itemGroupEntity = $paymentTransaction->getOfferPayment()->getOffer();
    }
}

我明白了:

Return value of Mockery_3_MyApp_Model_Entity_PaymentTransaction::getOfferPayment() must be an instance of MyApp\Model\Entity\OfferPayment, instance of Mockery_4__demeter_getOfferPayment returned


getOfferPayment 和 getOffer 的实现:

public function getOfferPayment() : OfferPayment
{
    return $this->offerPayment;
}


public function getOffer() : Offer
{
    return $this->offer;
}

【问题讨论】:

    标签: php unit-testing mocking mockery


    【解决方案1】:

    在这种情况下,Mockery 不支持return type declarations。 该问题可以通过删除 getter 的返回类型声明来解决:

    public function getOfferPayment()
    {
        return $this->offerPayment;
    }
    
    
    public function getOffer()
    {
        return $this->offer;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2015-11-02
      • 2021-09-13
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      相关资源
      最近更新 更多