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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With