Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test: Simulate a timeout with Guzzle 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?

like image 787
Victor Aguilar Avatar asked Sep 24 '15 22:09

Victor Aguilar


1 Answers

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

like image 103
Victor Aguilar Avatar answered Oct 27 '22 17:10

Victor Aguilar