如何将 Guzzle Mock Handler 传递给 PHP class 以测试具有 json 响应的 API 调用

How to pass Guzzle Mock Handler to a PHP class to test an API call that has json response

我有一个 php class,它使用 guzzle 调用 API 并得到响应:

public function getResponseToken()
{
    $response = $this->myGUzzleClient->request(
        'POST',
        '/token.php,
        [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'username' => $this->params['username'],
                'password' => $this->params['password'],
            ]
        ]
    );

    return json_decode($response->getBody()->getContents())->token;
}

我正在尝试使用 guzzle mock handler 测试此方法,这是我到目前为止所做的但没有奏效:

public function testGetResponseToken()
{

    $token = 'stringtoken12345stringtoken12345stringtoken12345';
    $mockHandler = new MockHandler([
        new Response(200, ['X-Foo' => 'Bar'], $token)
        ]
    );

    $handlerStack = HandlerStack::create($mockHandler);
    $client = new Client(['handler' => $handlerStack]);


    $myService = new MyService(
            new Logger('testLogger'),
            $client,
            $this->config
        );

        $this->assertEquals($token, $myService->getResponseToken());
}

我得到的错误是 "Trying to get property of non-object",所以在我看来 MyService 没有使用处理程序来进行调用。我究竟做错了什么?

class 在测试上下文之外按预期工作。还要注意客户端通常从 service.yml 注入到 MyService 中(我使用的是 symfony)。

您的处理程序工作正常,您只是模拟了错误的响应数据。您应该将响应设为原始 json.

尝试

$token = 'stringtoken12345stringtoken12345stringtoken12345';
    $mockHandler = new MockHandler(
    [
    new Response(200, ['X-Foo' => 'Bar'], \json_encode([ 'token' => $token ]))
    ]
);

现在应该可以了