Guzzler Testing Library

Guzzler Testing Library

Guzzler is a testing library specifically for Guzzle written by Adam Kelso:

Supercharge your app with a testing library specifically for Guzzle. Guzzler covers the process of setting up a mock handler, recording history of requests, and provides several convenience methods for creating expectations and assertions on that history.

Here’s an example from the documentation of how your tests might use the Guzzler library to mock and assert HTTP client requests and responses:

use GuzzleHttp\Psr7\Response;

// ...

$this->guzzler->expects($this->once())
    ->post('/some-url')
    ->withHeader('X-Authorization', 'some-key')
    ->willRespond(new Response(201));

In the context of a Laravel application you might have a base Guzzle client bound in the service container with an interface or concrete class, which you can override in your test suite:

public function setUp()
{
    parent::setUp();

    $this->client = $this->guzzler->getClient([
        "stream" => true,
        "base_uri" => "http://some-url.com/api/v2"
    ]);

    $this->app->instance(MyBaseClient::class, $this->client);
}

I like to have classes in my app that inject a Guzzle client dependency. I can add convenience methods to abstract requests and formatting, and then it relies on Guzzle for HTTP requests. This setup makes it easy to swap in something like Guzzler to mock the HTTP layer.

To learn more about this package including installation and usage, check out the documentation at guzzler.dev. You can check out the source code of this package on GitHub at blastcloud/guzzler.


Filed in: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Full-Stack Developer (PHP+JS)
Remote
The Interaction Design Foundation
Senior Laravel Developer
Remote
Sonar
Laravel / Vue.JS Developer - Join an amazing team!
Remote
JTR Solutions
Mid / Sen. Software Engineer
Clearwater, FL
ShineOn
Remote PHP / Laravel Developer
Remote
SpringboardVR
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Laravel Developer
Leidseplein, Amsterdam
Orderchamp.com