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 set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...