Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock responses for specific URLs with Guzzle?

The Guzzle 6 documentation gives an easy way to mock HTTP calls so that each request returns a specific response : http://docs.guzzlephp.org/en/latest/testing.html#mock-handler

However, as it is stated in the documentation, the MockHandler defines a queue of responses that will be sent for each request, whatever the URL, in the same order.

How to tell Guzzle to send a specific response for a given URL, each time it is called?

For instance, I want this call:

$client->request('GET', '/products')->getBody();

not to make the actual request but to always return:

{'products' => [{id: 1, name: 'Product 1'}, {id: 2, name: 'Product 2'}]

Doing it with the AngularJS $httpBackend service would be easy:

$httpBackend
    .when('GET', '/products')
    .respond("{id: 1, name: 'Product 1'}, {id: 2, name: 'Product 2'}")

Any idea on how to achieve this with Guzzle 6?

like image 271
Michaël Perrin Avatar asked Oct 09 '15 07:10

Michaël Perrin


1 Answers

With guzzle 6 you can also use a function as a handler! and the function passes the Request object so you can check the URL and return the proper response.

example:

        $client = new Client([
            'handler' => function (GuzzleHttp\Psr7\Request $request) {
                $path = $request->getUri()->getPath();

                if ($path === '/url1') {
                    return new GuzzleHttp\Psr7\Response(200, [], '{"body": "Url1"}');
                }

                if ($path === '/url2') {
                    return new GuzzleHttp\Psr7\Response(200, [], '{"body": "Url2"}');
                }
            }
        ]);

        $client->get('/url1');

I hope this helped someone.

like image 125
HSLM Avatar answered Sep 22 '22 14:09

HSLM