Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel extend TestResponse class

I'm trying to add a custom assertion to the TestReponse class so I can make something like this:

$response = $this->json('POST', '/foo/bar');

$response->myCustomAssertion();

I tried creating an App\TestResponse class that extends the original one and then binding it in the App\Provider\AppServiceProvider class.

public function register()
{
    $this->app->bind('Illuminate\Foundation\Testing\TestResponse', function ($app) {
        return new App\TestResponse();
    });
}

But $response->json() is still returning the original one and not my own implementation.

How can I extend the TestResponse class?

like image 459
Camilo Avatar asked Dec 03 '22 11:12

Camilo


2 Answers

If you want a little more fine-grained control, you can also extend the Illuminate\Foundation\Testing\TestResponse, as you have done, and then override the createTestResponse method in your TestCase class to return an instance of your custom response class:

// Laravel 8 and above
protected function createTestResponse($response)
{
    return tap(App\TestResponse::fromBaseResponse($response), function ($response) {
        $response->withExceptions(
            $this->app->bound(LoggedExceptionCollection::class)
                ? $this->app->make(LoggedExceptionCollection::class)
                : new LoggedExceptionCollection
        );
    });
}

// Before Laravel 8
protected function createTestResponse($response)
{
    return App\TestResponse::fromBaseResponse($response);
}

From Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.

like image 191
Jamie Rumbelow Avatar answered Dec 11 '22 11:12

Jamie Rumbelow


The TestResponse class uses the Macroable trait so you can add macro functions at runtime.

TestResponse::macro('nameOfFunction', function (...) {
    ...
});

You can add this to a Service Provider's boot method or somewhere before you need to make the call to that macro'ed method.

like image 26
lagbox Avatar answered Dec 11 '22 11:12

lagbox