guzzle/plugin-mock
guzzle/plugin-mock provides a mock plugin for Guzzle, letting you queue predefined responses and simulate HTTP requests during testing. Useful for isolating API clients, reproducing edge cases, and running fast, reliable unit tests without real network calls.
Installation:
composer require guzzle/plugin-mock:^3.0
(Note: This is for Guzzle 3.x—ensure compatibility with your project.)
Basic Mocking:
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
// Create a mock response
$mockResponse = new Response(200, [], 'Mocked response');
// Register the mock plugin
$mock = new MockPlugin();
$mock->addResponse($mockResponse);
$client = new Guzzle\Http\Client();
$client->addSubscriber($mock);
// Test the mock
$response = $client->get('http://example.com/api');
echo $response->getBody(); // Outputs: "Mocked response"
First Use Case:
Chaining Responses:
$mock->addResponse(new Response(200, [], 'First call'))
->addResponse(new Response(404, [], 'Second call'));
Conditional Mocking:
$mock->addResponse(
new Response(200, [], 'Success'),
'GET',
'/api/users',
['headers' => ['Accept' => 'application/json']]
);
Exception Simulation:
$mock->addResponse(new \RuntimeException('API down'));
Integration with Laravel:
// In a test case
$mock = new MockPlugin();
$mock->addResponse(new Response(200, [], json_encode(['data' => 'test'])));
$client = new GuzzleHttp\Client(['base_uri' => 'http://example.com']);
$client->getEmitter()->getEmitter()->addSubscriber($mock);
$response = $client->get('/api/endpoint');
$this->assertEquals('test', json_decode($response->getBody())->data);
Guzzle 3 vs. 6+:
php-mock-http or mockery.ClassNotFoundException for Guzzle\Http\Client.Case-Sensitive Matching:
$mock->addResponse($response, 'GET', '/api/Users'); // Fails if request is '/api/users'
Subscriber Order:
addSubscriber() early in the chain.No Persistent State:
MockPlugin.$mock->getResponses(); // Inspect registered responses.
$mock->getRequestCount(); // Check how many times a mock was triggered.
$client->addSubscriber(new \Guzzle\Plugin\Log\LogPlugin());
Custom Matchers:
Extend MockPlugin to add dynamic matching logic:
class CustomMockPlugin extends MockPlugin {
public function addDynamicResponse(Closure $callback) {
$this->responses[] = $callback;
}
}
Usage:
$mock->addDynamicResponse(function (RequestInterface $request) {
return new Response(200, [], 'Dynamic: ' . $request->getUri());
});
Delay Simulation: Simulate network latency:
$mock->addResponse(function () {
sleep(2); // Simulate 2-second delay
return new Response(200, [], 'Delayed response');
});
How can I help you explore Laravel packages today?