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]](https://laravel.com/cdn-cgi/l/email-protection), 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 feature 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. 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 Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use Tests\TestCase;
  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. }

Creating 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 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

Writing 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. 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. * 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. 'email_verified_at' => now(),
  24. 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
  25. 'remember_token' => Str::random(10),
  26. ];
  27. }
  28. }

As you can see, in their most basic form, factories are classes that extend Laravel’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.

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

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

Creating Models

Once you have defined your factories, you may use the static factory method provided by the Illuminate\Database\Eloquent\Factories\HasFactory trait on your Eloquent models in order to instantiate a factory instance for that model:

  1. namespace App\Models;
  2. use Illuminate\Database\Eloquent\Factories\HasFactory;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6. use HasFactory;
  7. }

Let’s take a look at a few examples of creating models. First, we’ll use the make method to create models without persisting them to the database:

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

You may create a collection of many models using the count method:

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

The HasFactory trait’s factory method will use conventions to determine the proper factory for the model. Specifically, the method will look for a factory in the Database\Factories namespace that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, you may overwrite the newFactory method on your model to return an instance of the model’s corresponding factory directly:

  1. /**
  2. * Create a new factory instance for the model.
  3. *
  4. * @return \Illuminate\Database\Eloquent\Factories\Factory
  5. */
  6. protected static function newFactory()
  7. {
  8. return \Database\Factories\Administration\FlightFactory::new();
  9. }

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 may simply call state methods directly:

  1. $users = User::factory()->count(5)->suspended()->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 = User::factory()->make([
  2. 'name' => 'Abigail Otwell',
  3. ]);

Alternatively, the state method may be called directly on the factory instance to perform an inline state transformation:

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

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

Persisting Models

The create method creates model instances and persists them to the database using Eloquent’s save method:

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

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

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

Sequences

Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a Sequence instance. For example, we may wish to alternate the value of an admin column on a User model between Y and N for each created user:

  1. use App\Models\User;
  2. use Illuminate\Database\Eloquent\Factories\Sequence;
  3. $users = User::factory()
  4. ->count(10)
  5. ->state(new Sequence(
  6. ['admin' => 'Y'],
  7. ['admin' => 'N'],
  8. ))
  9. ->create();

In this example, five users will be created with an admin value of Y and five users will be created with an admin value of N.

Factory Relationships

Relationships Within Definitions

You may attach relationships to models 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. use App\Models\User;
  2. /**
  3. * Define the model's default state.
  4. *
  5. * @return array
  6. */
  7. public function definition()
  8. {
  9. return [
  10. 'user_id' => User::factory(),
  11. 'title' => $this->faker->title,
  12. 'content' => $this->faker->paragraph,
  13. ];
  14. }

If the relationship’s columns depend on the factory that defines it you may provide a callback which accepts the evaluated attribute array:

  1. /**
  2. * Define the model's default state.
  3. *
  4. * @return array
  5. */
  6. public function definition()
  7. {
  8. return [
  9. 'user_id' => User::factory(),
  10. 'user_type' => function (array $attributes) {
  11. return User::find($attributes['user_id'])->type;
  12. },
  13. 'title' => $this->faker->title,
  14. 'content' => $this->faker->paragraph,
  15. ];
  16. }

Has Many Relationships

Next, let’s explore building Eloquent model relationships using Laravel’s fluent factory methods. First, let’s assume our application has a User model and a Post model. Also, let’s assume that the User model defines a hasMany relationship with Post. We can create a user that has three posts using the has method provided by the factory. The has method accepts a factory instance:

  1. use App\Models\Post;
  2. use App\Models\User;
  3. $users = User::factory()
  4. ->has(Post::factory()->count(3))
  5. ->create();

By convention, when passing a Post model to the has method, Laravel will assume that the User model must have a posts method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate:

  1. $users = User::factory()
  2. ->has(Post::factory()->count(3), 'posts')
  3. ->create();

Of course, you may perform state manipulations on the related models. In addition, you may pass a Closure based state transformation if your state change requires access to the parent model:

  1. $users = User::factory()
  2. ->has(
  3. Post::factory()
  4. ->count(3)
  5. ->state(function (array $attributes, User $user) {
  6. return ['user_type' => $user->type];
  7. })
  8. )
  9. ->create();

Using Magic Methods

For convenience, you may use the factory’s magic relationship methods to define relationships. For example, the following example will use convention to determine that the related models should be created via a posts relationship method on the User model:

  1. $users = User::factory()
  2. ->hasPosts(3)
  3. ->create();

When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models:

  1. $users = User::factory()
  2. ->hasPosts(3, [
  3. 'published' => false,
  4. ])
  5. ->create();

You may provide a Closure based state transformation if your state change requires access to the parent model:

  1. $users = User::factory()
  2. ->hasPosts(3, function (array $attributes, User $user) {
  3. return ['user_type' => $user->type];
  4. })
  5. ->create();

Belongs To Relationships

Now that we have explored how to build “has many” relationships using factories, let’s explore the inverse of the relationship. The for method may be used to define the model that factory created models belong to. For example, we can create three Post model instances that belong to a single user:

  1. use App\Models\Post;
  2. use App\Models\User;
  3. $posts = Post::factory()
  4. ->count(3)
  5. ->for(User::factory()->state([
  6. 'name' => 'Jessica Archer',
  7. ]))
  8. ->create();

Using Magic Methods

For convenience, you may use the factory’s magic relationship methods to define “belongs to” relationships. For example, the following example will use convention to determine that the three posts should belong to the user relationship on the Post model:

  1. $posts = Post::factory()
  2. ->count(3)
  3. ->forUser([
  4. 'name' => 'Jessica Archer',
  5. ])
  6. ->create();

Many To Many Relationships

Like has many relationships, “many to many” relationships may be created using the has method:

  1. use App\Models\Role;
  2. use App\Models\User;
  3. $users = User::factory()
  4. ->has(Role::factory()->count(3))
  5. ->create();

Pivot Table Attributes

If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the hasAttached method. This method accepts an array of pivot table attribute names and values as its second argument:

  1. use App\Models\Role;
  2. use App\Models\User;
  3. $users = User::factory()
  4. ->hasAttached(
  5. Role::factory()->count(3),
  6. ['active' => true]
  7. )
  8. ->create();

You may provide a Closure based state transformation if your state change requires access to the related model:

  1. $users = User::factory()
  2. ->hasAttached(
  3. Role::factory()
  4. ->count(3)
  5. ->state(function (array $attributes, User $user) {
  6. return ['name' => $user->name.' Role'];
  7. }),
  8. ['active' => true]
  9. )
  10. ->create();

Using Magic Methods

For convenience, you may use the factory’s magic relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a roles relationship method on the User model:

  1. $users = User::factory()
  2. ->hasRoles(1, [
  3. 'name' => 'Editor'
  4. ])
  5. ->create();

Polymorphic Relationships

Polymorphic relationships may also be created using factories. Polymorphic “morph many” relationships are created in the same way as typical “has many” relationships. For example, if a Post model has a morphMany relationship with a Comment model:

  1. use App\Models\Post;
  2. $post = Post::factory()->hasComments(3)->create();

Morph To Relationships

Magic methods may not be used to create morphTo relationships. Instead, the for method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the Comment model has a commentable method that defines a morphTo relationship. In this situation, we may create three comments that belong to a single post using the for method directly:

  1. $comments = Comment::factory()->count(3)->for(
  2. Post::factory(), 'commentable'
  3. )->create();

Polymorphic Many To Many Relationships

Polymorphic “many to many” relationships may be created just like non-polymorphic “many to many” relationships:

  1. use App\Models\Tag;
  2. use App\Models\Video;
  3. $users = Video::factory()
  4. ->hasAttached(
  5. Tag::factory()->count(3),
  6. ['public' => true]
  7. )
  8. ->create();

Of course, the magic has method may also be used to create polymorphic “many to many” relationships:

  1. $users = Video::factory()
  2. ->hasTags(3, ['public' => true])
  3. ->create();

Using Seeds

If you would like to use database seeders to populate your database during a feature 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 Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Foundation\Testing\WithoutMiddleware;
  5. use OrderStatusSeeder;
  6. use Tests\TestCase;
  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(OrderStatusSeeder::class);
  21. // ...
  22. }
  23. }

Available Assertions

Laravel provides several database assertions for your PHPUnit feature tests:

MethodDescription
$this->assertDatabaseCount($table, int $count);Assert that a table in the database contains the given amount of entries.
$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->assertDeleted($table, array $data);Assert that the given record has been deleted.
$this->assertSoftDeleted($table, array $data);Assert that the given record has been soft deleted.

For convenience, you may pass a model to the assertDeleted and assertSoftDeleted helpers to assert the record was deleted or soft deleted, respectively, from the database based on the model’s primary key.

For example, if you are using a model factory in your test, you may pass this model to one of these helpers to test your application properly deleted the record from the database:

  1. public function testDatabase()
  2. {
  3. $user = User::factory()->create();
  4. // Make call to application...
  5. $this->assertDeleted($user);
  6. }