5

I am using Guzzle 5.3 and want to test that my client throws a TimeOutException.

Then, how can I do a mock of Guzzle Client that throw a GuzzleHttp\Exception\ConnectException?

Code to test.

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:

The right question was: how to throw a Exception with Guzzle 5? or, how to test a catch block with Guzzle 5?

Victor Aguilar
  • 455
  • 4
  • 18
  • If you know the server's execution timeout value, why not try introducing php sleep or usleep to force a waiting time for an operation to finish? – Adam T Sep 25 '15 at 01:12
  • The time out is set in the `httpClient` with is created as well as the connection the server. I think it is not an good idea create/simulate a server when I have a mock of `httpClient` (Guzzle). Only have to know how throw a exception with this mock. – Victor Aguilar Sep 25 '15 at 15:41
  • Ok, understood. Sorry I can't be of more help here. – Adam T Sep 25 '15 at 18:41

1 Answers1

6

You can test code inside a catch block with help of the addException method in the GuzzleHttp\Subscriber\Mock object.

This is the full 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');
}

In the unit test, I add the GuzzleHttp\Exception\ConnectException to the mock. After, I add the mock to the emitter and, finally, I call the method I want test, request.

Reference:

Source Code

Mockito test a void method throws an exception

Community
  • 1
  • 1
Victor Aguilar
  • 455
  • 4
  • 18