Laravel 模拟多个 Guzzle 端点

Laravel mock multiple Guzzle endpoints

我正在使用 Laravel 6 并尝试测试端点。端点 正在向外部 API 发出 2 个请求(来自 mollie)。目前我 像这样模拟它:

抽象 BaseMollieEndpointTest

<?php

namespace Tests;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Mollie\Api\MollieApiClient;

abstract class BaseMollieEndpointTest extends TestCase
{
    /**
     * @var Client|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $guzzleClient;

    /**
     * @var MollieApiClient
     */
    protected $apiClient;

    protected function mockApiCall(Response $response)
    {
        $this->guzzleClient = $this->createMock(Client::class);

        $this->apiClient = new MollieApiClient($this->guzzleClient);

        $this->apiClient->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');

        $this->guzzleClient
            ->expects($this->once())
            ->method('send')
            ->with($this->isInstanceOf(Request::class))
            ->willReturnCallback(function (Request $request) use ($response) {
                return $response;
            });
    }
}

我所有的测试都是从那个 ^ 摘要 class 扩展而来的。我是这样实现的:

public function test()
{
    $this->mockApiCall(
        new Response(
            200,
            [],
            '{
              "response": "here is the response",
            }'
        )
    );

    Mollie::shouldReceive('api')
        ->once()
        ->andReturn(new MollieApiWrapper($this->app['config'], $this->apiClient));

    dd(Mollie::api()->customers()->get('238u3n'));
}

这是有效的。但问题是当我需要在同一个 api 调用中模拟另一个请求时,我得到相同的结果。

那么我怎样才能确保我可以模拟 2 个响应(而不是 1 个)并将其返回给特定的 url?

看看great Guzzler library for mocking HTTP calls, and also at MockHandler with history middleware

回答您的特定问题,使用 Guzzler 可以很简单:

$this->guzzler->expects($this->exactly(2))
    ->endpoint("/send", "POST")
    ->willRespond($response)
    ->willRespond(new Response(409));