Unit test: Simulate timeout with Guzzle 5

I am using Guzzle 5.3 and want to check what my client has chosen TimeOutException.

Then, how can I make a mock Guzzle client that throws GuzzleHttp\Exception\ConnectException?

Code to verify.

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();
    }
}

Update:

Correct question: how to throw an exception using Guzzle 5? or how to check catch block using Guzzle 5?

+4
source share
1 answer

You can check the code inside the block catchusing the method addExceptionin the object GuzzleHttp\Subscriber\Mock.

This is a complete test:

/**
 * @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');
}

unit test GuzzleHttp\Exception\ConnectException . , , , , request.

:

Mockito test void

+4

Source: https://habr.com/ru/post/1608904/


All Articles