单元测试:使用 Guzzle 5 模拟超时

Unit test: Simulate a timeout with Guzzle 5

我正在使用 Guzzle 5.3 并想测试我的客户端是否抛出 TimeOutException

那么,我怎样才能模拟 Guzzle Client 并抛出 GuzzleHttp\Exception\ConnectException

要测试的代码。

public function request($namedRoute, $data = [])
{
    try {
        /** @noinspection PhpVoidFunctionResultUsedInspection */
        /** @var \GuzzleHttp\Message\ResponseInterface $response */
        $response =  $this->httpClient->post($path, ['body' => $requestData]);
    } catch (ConnectException $e) {
        throw new \Vendor\Client\TimeOutException();
    }
}

更新:

正确的问题是:如何使用 Guzzle 5 抛出异常?或者,如何使用 Guzzle 5 测试 catch 块?

您可以在 GuzzleHttp\Subscriber\Mock 对象中的 addException 方法的帮助下测试 catch 块中的代码。

这是完整的测试:

/**
 * @expectedException \Vendor\Client\Exceptions\TimeOutException
 */
public function testTimeOut()
{
    $mock = new \GuzzleHttp\Subscriber\Mock();
    $mock->addException(
        new \GuzzleHttp\Exception\ConnectException(
            'Time Out',
            new \GuzzleHttp\Message\Request('post', '/')
        )
    );

    $this->httpClient
        ->getEmitter()
        ->attach($mock);

    $this->client = new Client($this->config, $this->routing, $this->httpClient);

    $this->client->request('any_route');
}

在单元测试中,我将 GuzzleHttp\Exception\ConnectException 添加到模拟中。之后,我将模拟添加到发射器,最后,我调用了我想要测试的方法,request.

参考:

Source Code

Mockito test a void method throws an exception