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

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Voxie
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Remote
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC
MassageBook