From 0b52c406615e0f41a7c8246bb4b993ae4ed1daf0 Mon Sep 17 00:00:00 2001 From: printempw Date: Wed, 15 Aug 2018 22:22:55 +0800 Subject: [PATCH] Add trait MockGuzzleClient for tests --- tests/Concerns/MockGuzzleClient.php | 64 +++++++++++++++++++++++++++++ tests/TestCase.php | 1 + 2 files changed, 65 insertions(+) create mode 100644 tests/Concerns/MockGuzzleClient.php diff --git a/tests/Concerns/MockGuzzleClient.php b/tests/Concerns/MockGuzzleClient.php new file mode 100644 index 00000000..f1c424f1 --- /dev/null +++ b/tests/Concerns/MockGuzzleClient.php @@ -0,0 +1,64 @@ +guzzleMockHandler = new MockHandler($responses); + $handler = HandlerStack::create($this->guzzleMockHandler); + $client = new Client(['handler' => $handler]); + + // Inject to Laravel service container + $this->app->instance(Client::class, $client); + } + + /** + * Add responses to Guzzle client's mock queue. + * Pass a Response or RequestException instance, or an array of them. + * + * @param array|Response|RequestException|integer $response + * @param array $headers + * @param string $body + * @param string $version + * @param string|null $reason + * @return void + */ + public function appendToGuzzleQueue($response = 200, $headers = [], $body = '', $version = '1.1', $reason = null) + { + if (! $this->guzzleMockHandler) { + $this->setupGuzzleClientMock(); + } + + if (is_array($response)) { + foreach ($response as $single) { + $this->appendToGuzzleQueue($single); + } + return; + } + + if ($response instanceof Response || $response instanceof RequestException) { + return $this->guzzleMockHandler->append($response); + } + + return $this->guzzleMockHandler->append(new Response($response, $headers, $body, $version, $reason)); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 51838667..eb9d470a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,6 +2,7 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase { + use MockGuzzleClient; use InteractsWithCache; /**