Skip to content

Instantly share code, notes, and snippets.

@macghriogair
Last active August 31, 2018 10:56
Show Gist options
  • Save macghriogair/08e9742af0358f28a43dd2981f2b9af2 to your computer and use it in GitHub Desktop.
Save macghriogair/08e9742af0358f28a43dd2981f2b9af2 to your computer and use it in GitHub Desktop.
Mocking Guzzle #tests #guzzle
<?php
namespace Tests;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
trait MockGuzzle
{
protected $mockGuzzle;
protected $txContainer;
protected function mockNextGuzzleRequest(Response $response)
{
$this->mockNextGuzzleRequests([$response]);
return $this;
}
protected function mockNextGuzzleRequests(array $responses)
{
foreach ($responses as $response) {
if (!($response instanceof Response)) {
throw new \RuntimeException("Response type incorrect.");
}
}
// Create a Handler for our fake responses
$mockHandler = new MockHandler($responses);
$stack = HandlerStack::create($mockHandler);
// Clear history of transactions
$this->txContainer = [];
$history = Middleware::history($this->txContainer);
// Add the history middleware to the handler stack.
$stack->push($history);
// Init new Client
$this->mockGuzzle = new Client(['handler' => $stack]);
return $this;
}
protected function assertTransactionCount(int $count)
{
$this->assertCount($count, $this->txContainer);
return $this;
}
protected function assertLastRequestMethod(string $method)
{
$this->assertEquals(strtoupper($method), $this->lastRequest()->getMethod());
return $this;
}
protected function assertLastRequestBody(array $fields)
{
$this->assertEquals($fields, json_decode($this->lastRequest()->getBody(), true));
return $this;
}
protected function lastTransaction()
{
return array_pop($this->txContainer);
}
protected function lastRequest()
{
$i = count($this->txContainer) - 1;
if (!isset($this->txContainer[$i])) {
throw new \OutOfBoundsException("No transactions for offset.");
}
return $this->txContainer[$i]['request'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment