php-guzzleHow to mock requests with Guzzle in PHP?
Mocking requests with Guzzle in PHP is a great way to test your application without making actual requests.
$mock = new \GuzzleHttp\Handler\MockHandler([
new \GuzzleHttp\Psr7\Response(200, [], '{"foo": "bar"}'),
]);
$handler = \GuzzleHttp\HandlerStack::create($mock);
$client = new \GuzzleHttp\Client(['handler' => $handler]);
$response = $client->request('GET', 'http://example.com');
echo $response->getBody();
Output example
{"foo": "bar"}
Code explanation
$mock: creates a new MockHandler instance with the given responses.$handler: creates a HandlerStack instance with the given handler.$client: creates a new Client instance with the given handler.$response: sends a request to the given URL and returns a response.getBody(): returns the body of the response.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
- How to install PHP Guzzle with Composer?
- How to install PHP Guzzle without Composer?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add query parameters to a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
See more codes...