Using Named Routes in a Lumen Test

Published on by

Using Named Routes in a Lumen Test image

When writing tests in Lumen, I recently discovered that the route() helper doesn’t work with tests out-of-the-box.

I prefer to define named routes and make requests against them in my tests. If you follow the Lumen documentation, the typical way that you make a request for a test looks like this:

$this->json('GET', '/posts/1')
->seeJson(['title' => 'Hello World']);

Using the route helper, your test might look like this:

public function testShowingAPost()
{
$this->json('GET', route('posts.show', ['id' => 1]))
->seeJson(['title' => "Hello World"]);
}

If you run the above test, here’s what the URL would return:

phpunit
PHPUnit 6.4.4 by Sebastian Bergmann and contributors.
 
.F 2 / 2 (100%)
 
Time: 48 ms, Memory: 6.00MB
 
There was 1 failure:
 
1) ExampleTest::testShowingAPost
Invalid JSON was returned from the route. Perhaps an exception was thrown?

If you inspect things a little closer, you can see the issue:

public function testShowingAPost()
{
$this->json('GET', route('posts.show', ['id' => 1]));
dd(
$this->response->getContent(),
route('posts.show', ['id' => 1])
);
 
$this->seeJson(['title' => "Hello World"]);
}

Interestingly, the route doesn’t look quite right, and the router is returning the / route:

phpunit
PHPUnit 6.4.4 by Sebastian Bergmann and contributors.
 
string(40) "Lumen (5.5.2) (Laravel Components 5.5.*)"
string(16) "http://:/posts/1"

It looks like the localhost part of the request isn’t being set, and the route isn’t matching. We can fix that by bootstrapping the request as Laravel does.

Bootstrapping the Request

When you run tests in the Laravel framework, the project includes CreatesApplication trait that gets called during setup which in turn bootstraps classes for the application. One of those “bootstrappers” is the SetRequestForConsole which bootstraps the request for the console.

We can replicate this functionality so that tests in Lumen have a bootstrapped request on setup, but it requires a little work on our end.

The base TestCase class eventually calls refreshApplication() during setup which in turn calls createApplication() defined in the tests/TestCase.php file.

The createApplication() method returns the application, so we can bootstrap the request at this point before returning the application and assigning it to $this->app.

Here’s what the default base TestCase class looks like that ships with Lumen:

<?php
 
abstract class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
}

Open the tests/TestCase.php file and update it to the following in order to replicate Laravel’s SetRequestForConsole:

<?php
 
use Illuminate\Http\Request;
use Laravel\Lumen\Testing\TestCase as BaseTestCase;
 
abstract class TestCase extends BaseTestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
 
$uri = $app->make('config')->get('app.url', 'http://localhost');
 
$components = parse_url($uri);
 
$server = $_SERVER;
 
if (isset($components['path'])) {
$server = array_merge($server, [
'SCRIPT_FILENAME' => $components['path'],
'SCRIPT_NAME' => $components['path'],
]);
}
 
$app->instance('request', Request::create(
$uri, 'GET', [], [], [], $server
));
 
return $app;
}
}

First, we require the application instance by assigning require to the $app variable. Instead of returning it, we create a request instance with a default URL of http://localhost.

When we re-run our tests, you should get the route that you’d expect from the dd() call we tried earlier:

phpunit
PHPUnit 6.4.4 by Sebastian Bergmann and contributors.
 
.string(23) "{"title":"Hello World"}"
string(24) "http://localhost/posts/1"

Now the original test using the route() helper will work as expected if you remove the dd() from the test case.

Configuration

If you want to make the application URL configurable, you could update the application to import a local configuration.

Let’s first create a config folder and copy the app configuration:

$ mkdir config/
$ cp vendor/laravel/lumen-framework/config/app.php config/

Next, open the config/app.php file and add the following somewhere to the array:

'url' => env('APP_URL', 'http://localhost'),

Last, you need to register the configuration file by adding the following line to the bootstrap/app.php file after the application instance is created:

$app->configure('app');

Learn More

Lumen’s testing API is around testing HTTP APIs and thus is slightly different yet familiar. To make Lumen more lightweight than Laravel, there are some differences and tradeoffs made. For example, Lumen uses the FastRoute package for the router instead of the router that ships with Laravel.

I feel that often Lumen is misunderstood as a micro-framework that is more generic, when in fact, it’s a framework for making APIs. Once you stick within those boundaries, Lumen can be a perfect fit for building APIs. I suggest reading over the whole manual, specifically the testing documentation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article