Created
April 7, 2020 20:11
-
-
Save PeterDKC/66185674d1fbd325341a74fd0b85aa9c to your computer and use it in GitHub Desktop.
Helper method to Mock a Guzzle Client in a PHPUnit test within a Laravel Application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Unit; | |
use Tests\TestCase; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\HandlerStack; | |
use GuzzleHttp\Psr7\Response; | |
use GuzzleHttp\Handler\MockHandler; | |
class MyUnitTest extends TestCase | |
{ | |
/** | |
* @test | |
*/ | |
function testThatThingsHappen() | |
{ | |
$responseString = '{"id": 10, "name": "Bob Edwards"}'; | |
$response = new Response( | |
200, | |
['headers' => ['Authorization' => 'Bearer Foo']], | |
$responseString | |
); | |
$this->mockClient($response); | |
// $this->mockClient([$response, $secondResponse, $etc]); For Multiple Responses | |
$request = app(Client::class)->get('endpoint'); | |
$response = json_decode((string) $request->getBody()); | |
$this->assertEquals( | |
'Bob Edwards', | |
$response->name | |
); | |
} | |
protected function mockClient($responses) | |
{ | |
// fluff and sanitize parameter | |
if (! is_array($responses)) { | |
$responses = [$responses]; | |
} | |
foreach ($responses as $response) { | |
if (!$response instanceOf Response) { | |
throw new \Exception('Passed Responses must be an instance of \GuzzleHttp\Psr7\Response.'); | |
} | |
} | |
// mock everything | |
$mockHandler = new MockHandler($responses); | |
$handlerStack = HandlerStack::create($mockHandler); | |
$client = new Client(['handler' => $handlerStack]); | |
app()->instance(Client::class, $client); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment