如何模拟其他模拟的属性?

时间:2018-09-09 08:41:53

标签: php unit-testing phpunit mockery

有人知道我如何模拟模拟的属性吗?

我下面的存储库需要一个ApiClient实例,并在其属性上调用一个方法:

<?php

class PaymentRepository
{
    public function __construct(ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
    }

    public function create()
    {
        return $this->apiClient->payments->create('args');
    }
}

我可以模拟ApiClient的实例并将其注入到PaymentRepository中,但是如何设置对其属性payments调用的方法的期望呢?

在模拟属性上设置新模拟似乎无效:

<?php

class PaymentRepositoryTest
{
    public function test_it_can_create_payments()
    {
        $apiClient = Mockery::mock(ApiClient::class);
        $paymentsEndpoint = M::mock(PaymentsEndpoint::class);
        $paymentsEndpoint->shouldReceive('create')
            ->with('args')
            ->once()
            ->andReturn(true);
        $apiClient->payments = $paymentsEndpoint;

        $payments = new PaymentRepository($apiClient);

        $this->assertTrue($payments->create());
    }
}

但是我得到了错误:

Error : Call to a member function create() on null

我也尝试过模拟,就像可以模拟方法链一样,但是Mockery仅支持链接方法。

<?php

class PaymentRepositoryTest
{
    public function test_it_can_create_payments()
    {
        $apiClient = Mockery::mock(ApiClient::class);
        $apiClient->shouldReceive('payments->create')
            ->with('args')
            ->once()
            ->andReturn(true);

        $payments = new PaymentRepository($apiClient);

        $this->assertTrue($payments->create());
    }
}

我该如何解决?我该如何设置对模拟财产的期望?

0 个答案:

没有答案