Search code examples
phplaravelunit-testingguzzle

How to create mock request for Guzzle in UnitTest? (PHP, Laravel)


Issue description:

It is not possible to create Mock request in UnitTest. I'm using Guzzle in Laravel.

I am sanding request in Laravel with Guzzle. This is in code file class. Example:

$client = new Client(['cookies' => true]);
    $client->request('GET', 'https://some-test-url.com/provider/v2/oauth2/authorize',
      ['connect_timeout' => 30]);

In UnitTest class file in test, I'm creating Mock request.

$mock = new MockHandler([
        new Response(200,
          ['Set-Cookie' => 'cookie1=cookie1_data; Domain=some-test-url.com',
          'cookie2=cookie2_data; Domain=some-test-url.com',
          'cookie3=cookie3_data; Domain=some-test-url.com',] , 'Test response'),
    ]);

    $handlerStack = HandlerStack::create($mock);
    $client = new Client(['handler' => $handlerStack, 'cookies' => true]);

After running UnitTest the test are passing. The issue is that Mock request is not implemented. The test is hitting API URL: https://some-test-url.com/provider/v2/oauth2/authorize. When I turn off the internet I'm getting error:

 cURL error 6: Could not resolve host: some-test-url.com (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://some-test-url.com/provider/v2/oauth2/authorize

I want to crate UnitTests and that tests are reading Mock data and not hitting the API.

Do you know is it possible to write mock test for Guzzle in Laravel? If it is how can I do it?


Solution

  • Issue Solved

    I have instanced two Clients. For creating valid test I needed to use same Client for tests class and in code class.