Database Testing

Introduction

Laravel provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the assertDatabaseHas helper to assert that data exists in the database matching a given set of criteria. For example, if you would like to verify that there is a record in the users table with the email value of [email protected], you can do the following:

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

You can also use the assertDatabaseMissing helper to assert that data does not exist in the database.

The assertDatabaseHas 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.

Generating Factories

To create a factory, use the make:factory Artisan command:

  1. php artisan make:factory PostFactory

The new factory will be placed in your database/factories directory.

The —model option may be used to indicate the name of the model created by the factory. This option will pre-fill the generated factory file with the given model:

  1. php artisan make:factory PostFactory --model=Post

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. The RefreshDatabase trait takes the most optimal approach to migrating your test database depending on if you are using an in-memory database or a traditional database. Use the trait on your test class and everything will be handled for you:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use Illuminate\Foundation\Testing\RefreshDatabase;
  5. use Illuminate\Foundation\Testing\WithoutMiddleware;
  6. class ExampleTest extends TestCase
  7. {
  8. use RefreshDatabase;
  9. /**
  10. * A basic functional test example.
  11. *
  12. * @return void
  13. */
  14. public function testBasicExample()
  15. {
  16. $response = $this->get('/');
  17. // ...
  18. }
  19. }

Writing Factories

When testing, you may 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, Laravel 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 one factory definition:

  1. use Illuminate\Support\Str;
  2. use Faker\Generator as Faker;
  3. $factory->define(App\User::class, function (Faker $faker) {
  4. return [
  5. 'name' => $faker->name,
  6. 'email' => $faker->unique()->safeEmail,
  7. 'email_verified_at' => now(),
  8. 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
  9. 'remember_token' => Str::random(10),
  10. ];
  11. });

Within the Closure, which serves as the factory definition, you may return the default test values of all attributes on the model. The Closure will receive an instance of the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing.

You may also create additional factory files for each model for better organization. For example, you could create UserFactory.php and CommentFactory.php files within your database/factories directory. All of the files within the factories directory will automatically be loaded by Laravel.

{tip} You can set the Faker locale by adding a faker_locale option to your config/app.php configuration file.

Factory States

States 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 delinquent state that modifies one of its default attribute values. You may define your state transformations using the state method. For simple states, you may pass an array of attribute modifications:

  1. $factory->state(App\User::class, 'delinquent', [
  2. 'account_status' => 'delinquent',
  3. ]);

If your state requires calculation or a $faker instance, you may use a Closure to calculate the state's attribute modifications:

  1. $factory->state(App\User::class, 'address', function ($faker) {
  2. return [
  3. 'address' => $faker->address,
  4. ];
  5. });

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. For example, you may use callbacks to relate additional models to the created model:

  1. $factory->afterMaking(App\User::class, function ($user, $faker) {
  2. // ...
  3. });
  4. $factory->afterCreating(App\User::class, function ($user, $faker) {
  5. $user->accounts()->save(factory(App\Account::class)->make());
  6. });

You may also define callbacks for factory states:

  1. $factory->afterMakingState(App\User::class, 'delinquent', function ($user, $faker) {
  2. // ...
  3. });
  4. $factory->afterCreatingState(App\User::class, 'delinquent', function ($user, $faker) {
  5. // ...
  6. });

Using Factories

Creating Models

Once you have defined your factories, you may use the global factory function in your tests or seed files to generate model instances. So, let's take a look at a few examples of creating models. First, we'll use the make method to create models but not save them to the database:

  1. public function testDatabase()
  2. {
  3. $user = factory(App\User::class)->make();
  4. // Use model in tests...
  5. }

You may also create a Collection of many models or create models of a given type:

  1. // Create three App\User instances...
  2. $users = factory(App\User::class, 3)->make();

Applying States

You may also apply any of your states to the models. If you would like to apply multiple state transformations to the models, you should specify the name of each state you would like to apply:

  1. $users = factory(App\User::class, 5)->states('delinquent')->make();
  2. $users = factory(App\User::class, 5)->states('premium', 'delinquent')->make();

Overriding Attributes

If you would like to override some of the default values of your models, you may pass an array of values to the make method. Only the specified values will be replaced while the rest of the values remain set to their default values as specified by the factory:

  1. $user = factory(App\User::class)->make([
  2. 'name' => 'Abigail',
  3. ]);

{tip} Mass assignment protection is automatically disabled when creating models using factories.

Persisting Models

The create method not only creates the model instances but also saves them to the database using Eloquent's save method:

  1. public function testDatabase()
  2. {
  3. // Create a single App\User instance...
  4. $user = factory(App\User::class)->create();
  5. // Create three App\User instances...
  6. $users = factory(App\User::class, 3)->create();
  7. // Use model in tests...
  8. }

You may override attributes on the model by passing an array to the create method:

  1. $user = factory(App\User::class)->create([
  2. 'name' => 'Abigail',
  3. ]);

Relationships

In this example, we'll attach a relation to some created models. When using the create method to create multiple models, an Eloquent collection instance is returned, allowing you to use any of the convenient functions provided by the collection, such as each:

  1. $users = factory(App\User::class, 3)
  2. ->create()
  3. ->each(function ($user) {
  4. $user->posts()->save(factory(App\Post::class)->make());
  5. });

You may use the createMany method to create multiple related models:

  1. $user->posts()->createMany(
  2. factory(App\Post::class, 3)->make()->toArray()
  3. );

Relations & Attribute Closures

You may also attach relationships to models using Closure attributes in your factory definitions. For example, if you would like to create a new User instance when creating a Post, you may do the following:

  1. $factory->define(App\Post::class, function ($faker) {
  2. return [
  3. 'title' => $faker->title,
  4. 'content' => $faker->paragraph,
  5. 'user_id' => function () {
  6. return factory(App\User::class)->create()->id;
  7. }
  8. ];
  9. });

These Closures also receive the evaluated attribute array of the factory that defines them:

  1. $factory->define(App\Post::class, function ($faker) {
  2. return [
  3. 'title' => $faker->title,
  4. 'content' => $faker->paragraph,
  5. 'user_id' => function () {
  6. return factory(App\User::class)->create()->id;
  7. },
  8. 'user_type' => function (array $post) {
  9. return App\User::find($post['user_id'])->type;
  10. }
  11. ];
  12. });

Using Seeds

If you would like to use database seeders to populate your database during a test, you may use the seed method. By default, the seed method will return the DatabaseSeeder, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the seed method:

  1. <?php
  2. namespace Tests\Feature;
  3. use Tests\TestCase;
  4. use OrderStatusesTableSeeder;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Illuminate\Foundation\Testing\WithoutMiddleware;
  7. class ExampleTest extends TestCase
  8. {
  9. use RefreshDatabase;
  10. /**
  11. * Test creating a new order.
  12. *
  13. * @return void
  14. */
  15. public function testCreatingANewOrder()
  16. {
  17. // Run the DatabaseSeeder...
  18. $this->seed();
  19. // Run a single seeder...
  20. $this->seed(OrderStatusesTableSeeder::class);
  21. // ...
  22. }
  23. }

Available Assertions

Laravel provides several database assertions for your PHPUnit tests:

MethodDescription
$this->assertDatabaseHas($table, array $data);Assert that a table in the database contains the given data.
$this->assertDatabaseMissing($table, array $data);Assert that a table in the database does not contain the given data.
$this->assertSoftDeleted($table, array $data);Assert that the given record has been soft deleted.