Testing

Introduction

Lumen is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box, and a phpunit.xml file is already setup for your application. The framework also ships with convenient helper methods allowing you to expressively test your application’s JSON responses.

An ExampleTest.php file is provided in the tests directory. After installing a new Lumen application, simply run phpunit on the command line to run your tests.

Test Environment

Lumen automatically configures the cache to the array driver while testing, meaning no cache data will be persisted while testing.

You are free to create other testing environment configurations as necessary. The testing environment variables may be configured in the phpunit.xml file.

Defining & Running Tests

To create a test case, simply create a new test file in the tests directory. The test class should extend TestCase. You may then define test methods as you normally would using PHPUnit. To run your tests, simply execute the phpunit command from your terminal:

  1. <?php
  2. class FooTest extends TestCase
  3. {
  4. public function testSomethingIsTrue()
  5. {
  6. $this->assertTrue(true);
  7. }
  8. }

Note: If you define your own setUp method within a test class, be sure to call parent::setUp.

Application Testing

Lumen provides a very fluent API for making HTTP requests to your application and examining the output.

Testing JSON APIs

Lumen also provides several helpers for testing JSON APIs and their responses. For example, the get, post, put, patch, and delete methods may be used to issue requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let’s write a test to make a POST request to /user and assert that a given array was returned in JSON format:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $this->json('POST', '/user', ['name' => 'Sally'])
  12. ->seeJson([
  13. 'created' => true,
  14. ]);
  15. }
  16. }

The seeJson method converts the given array into JSON, and then verifies that the JSON fragment occurs anywhere within the entire JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

Verify Exact JSON Match

If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the seeJsonEquals method:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. /**
  5. * A basic functional test example.
  6. *
  7. * @return void
  8. */
  9. public function testBasicExample()
  10. {
  11. $this->post('/user', ['name' => 'Sally'])
  12. ->seeJsonEquals([
  13. 'created' => true,
  14. ]);
  15. }
  16. }

Authentication

The actingAs helper method provides a simple way to authenticate a given user as the current user:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testApplication()
  5. {
  6. $user = factory('App\User')->create();
  7. $this->actingAs($user)
  8. ->get('/user');
  9. }
  10. }

Custom HTTP Requests

If you would like to make a custom HTTP request into your application and get the full Illuminate\Http\Response object, you may use the call method:

  1. public function testApplication()
  2. {
  3. $response = $this->call('GET', '/');
  4. $this->assertEquals(200, $response->status());
  5. }

If you are making POST, PUT, or PATCH requests you may pass an array of input data with the request. Of course, this data will be available in your routes and controller via the Request instance:

  1. $response = $this->call('POST', '/user', ['name' => 'Taylor']);

Working With Databases

Lumen also provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the seeInDatabase helper to assert that data exists in the database matching a given set of criteria. For example, if we would like to verify that there is a record in the users table with the email value of [[email protected]](https://lumen.laravel.com/cdn-cgi/l/email-protection), we can do the following:

  1. public function testDatabase()
  2. {
  3. // Make call to application...
  4. $this->seeInDatabase('users', ['email' => '[email protected]']);
  5. }

Of course, the seeInDatabase method and other helpers like it are for convenience. You are free to use any of PHPUnit’s built-in assertion methods to supplement your tests.

Resetting The Database After Each Test

It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests.

Using Migrations

One option is to rollback the database after each test and migrate it before the next test. Lumen provides a simple DatabaseMigrations trait that will automatically handle this for you. Simply use the trait on your test class:

  1. <?php
  2. use Laravel\Lumen\Testing\DatabaseMigrations;
  3. use Laravel\Lumen\Testing\DatabaseTransactions;
  4. class ExampleTest extends TestCase
  5. {
  6. use DatabaseMigrations;
  7. /**
  8. * A basic functional test example.
  9. *
  10. * @return void
  11. */
  12. public function testBasicExample()
  13. {
  14. $this->get('/foo');
  15. }
  16. }

Using Transactions

Another option is to wrap every test case in a database transaction. Again, Lumen provides a convenient DatabaseTransactions trait that will automatically handle this:

  1. <?php
  2. use Laravel\Lumen\Testing\DatabaseMigrations;
  3. use Laravel\Lumen\Testing\DatabaseTransactions;
  4. class ExampleTest extends TestCase
  5. {
  6. use DatabaseTransactions;
  7. /**
  8. * A basic functional test example.
  9. *
  10. * @return void
  11. */
  12. public function testBasicExample()
  13. {
  14. $this->get('/foo');
  15. }
  16. }

Model Factories

When testing, it is common to need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Lumen allows you to define a default set of attributes for each of your Eloquent models using model factories.

To get started, take a look at the database/factories/UserFactory.php file in your application. Out of the box, this file contains the following factory definition:

  1. <?php
  2. namespace Database\Factories;
  3. use App\Models\User;
  4. use Illuminate\Database\Eloquent\Factories\Factory;
  5. class UserFactory extends Factory
  6. {
  7. /**
  8. * The name of the factory's corresponding model.
  9. *
  10. * @var string
  11. */
  12. protected $model = User::class;
  13. /**
  14. * Define the model's default state.
  15. *
  16. * @return array
  17. */
  18. public function definition()
  19. {
  20. return [
  21. 'name' => $this->faker->name,
  22. 'email' => $this->faker->unique()->safeEmail,
  23. ];
  24. }
  25. }

As you can see, in their most basic form, factories are classes that extend Lumen’s base factory class and define a model property and definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory.

Via the faker property, factories have access to the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing.

Factory States

State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your User model might have a suspended state that modifies one of its default attribute values. You may define your state transformations using the base factory’s state method. You may name your state method anything you like. After all, it’s just a typical PHP method:

  1. /**
  2. * Indicate that the user is suspended.
  3. *
  4. * @return \Illuminate\Database\Eloquent\Factories\Factory
  5. */
  6. public function suspended()
  7. {
  8. return $this->state([
  9. 'account_status' => 'suspended',
  10. ]);
  11. }

If your state transformation requires access to the other attributes defined by the factory, you may pass a callback to the state method. The callback will receive the array of raw attributes defined for the factory:

  1. /**
  2. * Indicate that the user is suspended.
  3. *
  4. * @return \Illuminate\Database\Eloquent\Factories\Factory
  5. */
  6. public function suspended()
  7. {
  8. return $this->state(function (array $attributes) {
  9. return [
  10. 'account_status' => 'suspended',
  11. ];
  12. });
  13. }

Factory Callbacks

Factory callbacks are registered using the afterMaking and afterCreating methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a configure method on the factory class. This method will automatically be called by Laravel when the factory is instantiated:

  1. namespace Database\Factories;
  2. use App\Models\User;
  3. use Illuminate\Database\Eloquent\Factories\Factory;
  4. use Illuminate\Support\Str;
  5. class UserFactory extends Factory
  6. {
  7. /**
  8. * The name of the factory's corresponding model.
  9. *
  10. * @var string
  11. */
  12. protected $model = User::class;
  13. /**
  14. * Configure the model factory.
  15. *
  16. * @return $this
  17. */
  18. public function configure()
  19. {
  20. return $this->afterMaking(function (User $user) {
  21. //
  22. })->afterCreating(function (User $user) {
  23. //
  24. });
  25. }
  26. // ...
  27. }

Using Factories In Tests

The Lumen model factories based on the same code as the Laravel model factories. Therefore, please consult the full Laravel documentation for usage examples.

Mocking

Mocking Events

If you are making heavy use of Lumen’s event system, you may wish to silence or mock certain events while testing. For example, if you are testing user registration, you probably do not want all of a UserRegistered event’s handlers firing, since these may send “welcome” e-mails, etc.

Lumen provides a convenient expectsEvents method that verifies the expected events are fired, but prevents any handlers for those events from running:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testUserRegistration()
  5. {
  6. $this->expectsEvents('App\Events\UserRegistered');
  7. // Test user registration code...
  8. }
  9. }

If you would like to prevent all event handlers from running, you may use the withoutEvents method:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testUserRegistration()
  5. {
  6. $this->withoutEvents();
  7. // Test user registration code...
  8. }
  9. }

Mocking Jobs

Sometimes, you may wish to simply test that specific jobs are dispatched by your controllers when making requests to your application. This allows you to test your routes / controllers in isolation - set apart from your job’s logic. Of course, you can then test the job itself in a separate test class.

Lumen provides a convenient expectsJobs method that will verify that the expected jobs are dispatched, but the job itself will not be executed:

  1. <?php
  2. class ExampleTest extends TestCase
  3. {
  4. public function testPurchasePodcast()
  5. {
  6. $this->expectsJobs('App\Jobs\PurchasePodcast');
  7. // Test purchase podcast code...
  8. }
  9. }

Note: This method only detects jobs that are dispatched via the dispatch global helper function or the $this->dispatch method from a route or controller. It does not detect jobs that are sent directly to Queue::push.

Mocking Facades

When testing, you may often want to mock a call to a Lumen facade. For example, consider the following controller action:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Cache;
  4. class UserController extends Controller
  5. {
  6. /**
  7. * Show a list of all users of the application.
  8. *
  9. * @return Response
  10. */
  11. public function index()
  12. {
  13. $value = Cache::get('key');
  14. //
  15. }
  16. }

We can mock the call to the Cache facade by using the shouldReceive method, which will return an instance of a Mockery mock. Since facades are actually resolved and managed by the Lumen service container, they have much more testability than a typical static class. For example, let’s mock our call to the Cache facade:

  1. <?php
  2. class FooTest extends TestCase
  3. {
  4. public function testGetIndex()
  5. {
  6. Cache::shouldReceive('get')
  7. ->once()
  8. ->with('key')
  9. ->andReturn('value');
  10. $this->get('/users');
  11. }
  12. }

Note: You should not mock the Request facade. Instead, pass the input you desire into the HTTP helper methods such as call and post when running your test.