Laravel testing requests

Viewed 186

I'm working on a large Laravel app, currently on v8.45.1 which has never had tests, so I'm working to get it to a point where we can start writing unit & feature tests.

I'm hitting an issue where the two request classes (App\Core\Request and App\Core\FormRequest) both use a trait RequestTrait which holds a set of utility methods.

This obviously works fine in local/staging/production, but when I run the test suite it complains that none of the methods provided by the trait exist:

Method Illuminate\Http\Request::isFromTrustedSource does not exist.

They are being called in various places as Request::isFromTrustedSource() or request()->isFromTrustedSource().

I can imagine that when running the app in the test environment, there may be differences to the request. Is it using a different class, or does the trait not apply for some reason?

1 Answers

I think, I found your problem - App\Core\Request extends Illuminate\Http\Request and in index.php you use App\Core\Request

The problem is in Illuminate\Foundation\Testing\Concerns\MakesHttpRequests::call()

When you use $this->get(...) in test suite - this method bootstrap app with standard request - not with your App\Core\Request

You can override this method in base tests/TestCase.php and pass your own request.

Unfortunately, it has no contract, than you cannot work with this through $this->app->bind()

Something like this:

class TestCase extends BaseTestCase
{
    public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
    {
    //other code
    $response = $kernel->handle(
        $request = \App\Core\Request::createFromBase($symfonyRequest)
    );
    //other code
    }
}
Related