30 Days of Automated Testing:Using PHPUnit【D15】

Seeder: Sowing

WilliamP
2 min readJan 29, 2023

Today, let’s take a look at the seeder!

What Is Seeder

The Seeder is a feature provided by Laravel that allows batch creation of test data. It allows us to put the logic for creating test data into a seeder class, making it easy to reuse to create specific data.

Example of Seeder

  • Create Seeder Command
php artisan make:seeder UserSeeder
  • database/seeders/UserSeeder.php
<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\UserLog;
use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$users = User::factory()
->count(10)
->create();

foreach ($users as $user) {
UserLog::factory()
->count(5)
->create([
'user_id' => $user->id
]);
}
}
}

In the above seeder code, the run() function is the main logic block for the seeder. In this seeder, we implemented a logic to create 10 user records using the Model Factory, and also create 5 logs for each user data.

  • tests/Feature/UserTest.php
<?php

namespace Tests\Feature;

use Database\Seeders\UserSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserTest extends TestCase
{
use RefreshDatabase;

public function testUserSeeder()
{
$this->seed(UserSeeder::class);

// Skip
}

public function testUserSeeder2()
{
$this->seed(UserSeeder::class);

// Skip
}
}

The above test code calls the UserSeeder seeder to create data. When multiple test case functions require a specific group of data, using a seeder to create test data can avoid duplicating the creation of test data logic scattered in different test case functions.

Besides calling the seeder in the test code, you can also seed the data using commands.

php artisan db:seed --class=UserSeeder

In addition, you can also call other seeders from seeder A:


<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::factory()
->count(10)
->create();

foreach ($users as $user) {
UserLog::factory()
->count(5)
->create([
'user_id' => $user->id
]);
}

// Assuming that there is another implementation of a seeder called PostSeeder.
$this->call([
PostSeeder::class,
]);
}
}

That concludes today’s introduction to seeders in Laravel. You can make good use of seeders to streamline your testing process.

Next, let’s take a look at some mocking techniques!

If you liked this article or found it helpful, feel free to give it some claps and follow the author!

Reference

Articles of This Series

--

--