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

Vic*_*lar 4 php unit-testing timeout exception guzzle

我正在使用Guzzle 5.3,并想测试我的客户端抛出一个TimeOutException.

然后,我怎么能模拟Guzzle客户端抛出一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

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

Vic*_*lar 5

您可以catch借助对象中的addException方法测试块内的代码GuzzleHttp\Subscriber\Mock.

这是完整的测试:

/**
 * @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');
}
Run Code Online (Sandbox Code Playgroud)

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

参考:

源代码

Mockito测试void方法会抛出异常