Introduction to Seeding Data in Testing

Tutorials

April 8th, 2017

seeder-leader.jpg

Since seeding was released in Laravel 5.1, testing has become easier and quicker.

You can have ten users with each having a post or 1000 users with one or more posts inserted before the testing begins.

In this tutorial, you will create a test case to test the user model and a seeder to seed ten users, and each is following one user into the database.

First things first, we need to create the database tables.

Migration

Create a table to store the relationship between users (who is following who).

1# database/migrations/2014_10_12_000000_create_users_table.php
2class CreateUsersTable extends Migration
3{
4 /**
5 * Run the migrations.
6 *
7 * @return void
8 */
9 public function up()
10 {
11 Schema::create('users', function (Blueprint $table) {
12 $table->increments('id');
13 $table->string('name');
14 $table->string('email')->unique();
15 $table->string('password');
16 $table->rememberToken();
17 $table->timestamps();
18 });
19
20 // following table is storing the relationship between users
21 // user_id is following follow_user_id
22 Schema::create('following', function (Blueprint $table) {
23 $table->integer('user_id')->unsigned()->index();
24 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
25
26 $table->integer('follow_user_id')->unsigned()->index();
27 $table->foreign('follow_user_id')->references('id')->on('users')->onDelete('cascade');
28
29 $table->timestamps();
30 });
31 }
32
33 /**
34 * Reverse the migrations.
35 *
36 * @return void
37 */
38 public function down()
39 {
40 Schema::dropIfExists('following');
41 Schema::dropIfExists('users');
42 }
43}

Next, run the migration.

1php artisan migrate
2Migration table created successfully.

If your application version is 5.4, and you see the error below:

1[Illuminate\Database\QueryException]
2
3SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
4[PDOException]
5SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Don’t panic! Check out this article for the workaround.

After you’ve applied the workaround, drop the previously created tables and run the migration again.

1php artisan migrate
2Migration table created successfully.
3Migrated: 2014_10_12_000000_create_users_table
4Migrated: 2014_10_12_100000_create_password_resets_table

The database is ready. Now, let’s prepare the user model.

User Model

The user model is the testing subject in this case, and it has a few methods to create and retrieve relationships among users.

1# app/User.php
2class User extends Authenticatable
3{
4 use Notifiable;
5
6 /**
7 * The attributes that are mass assignable.
8 *
9 * @var array
10 */
11 protected $fillable = [
12 'name', 'email', 'password',
13 ];
14
15 /**
16 * The attributes that should be hidden for arrays.
17 *
18 * @var array
19 */
20 protected $hidden = [
21 'password', 'remember_token',
22 ];
23
24 public function follows(User $user)
25 {
26 $this->following()->attach($user->id);
27 }
28
29 public function unfollows(User $user)
30 {
31 $this->following()->detach($user->id);
32 }
33
34 public function following()
35 {
36 return $this->belongsToMany('App\User', 'following', 'user_id', 'follow_user_id')->withTimestamps();
37 }
38
39 public function isFollowing(User $user)
40 {
41 return !is_null($this->following()->where('follow_user_id', $user->id)->first());
42 }
43}

The user model is ready to test. Next, we’ll insert data into the database.

Seeding

Laravel makes it pretty easy to perform seeding. A seeder class contains a run method by default. You can insert data by using a query builder or Eloquent model factories.

Let’s run an Artisan command to generate a seeder.

1php artisan make:seeder UsersTableSeeder

Then, you use the model factory to generate ten users in the run method.

1# database/seeds/UsersTableSeeder.php
2use App\User;
3use Illuminate\Database\Seeder;
4
5class UsersTableSeeder extends Seeder
6{
7 /**
8 * Run the database seeds.
9 *
10 * @return void
11 */
12 public function run()
13 {
14 $users = factory(User::class, 10)->create();
15 }
16}

Run the artisan command to perform seeding.

1php artisan db:seed --class=UsersTableSeeder

You can also enable the calling to UsersTableSeeder in DatabaseSeeder run method.

1# database/seeds/UsersTableSeeder.php
2use App\User;
3use Illuminate\Database\Seeder;
4
5class UsersTableSeeder extends Seeder
6{
7 /**
8 * Run the database seeds.
9 *
10 * @return void
11 */
12 public function run()
13 {
14 $users = factory(User::class, 10)->create();
15 }
16}

Run the artisan command to perform seeding.

1php artisan db:seed --class=UsersTableSeeder

You can also enable the calling to UsersTableSeeder in DatabaseSeeder run method.

1# database/seeds/DatabaseSeeder.php
2class DatabaseSeeder extends Seeder
3{
4 /**
5 * Run the database seeds.
6 *
7 * @return void
8 */
9 public function run()
10 {
11 $this->call(UsersTableSeeder::class);
12 }
13}

Next, run the command without declaring the seeder class name.

1php artisan db:seed

With DatabaseSeeder, you may execute multiple seeder classes.

Now, we’re going to work on our test case.

Test Case

In this tutorial, your test case’s objective is testing the follow and unfollow methods in the user model.

We’re going to begin by generating a new test.

1php artisan make:test UserTest

Prerequisite Test

First, we’ll create a test to ensure there are ten users in the database.

1# tests/Feature/UserTest.php
2use App\User;
3
4class UserTest extends TestCase
5{
6 public function test_have_10_users()
7 {
8 $this->assertEquals(10, User::count());
9 }
10}

Run PHPUnit.

1phpunit

If it doesn’t work, try this.

1vendor/bin/phpunit
2PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
3... 3 / 3 (100%)
4Time: 2.72 seconds, Memory: 12.00MB
5OK (3 tests, 3 assertions)

Why doesn’t PHPUnit work? Perhaps your machine’s version doesn’t meet Laravel’s requirement. Laravel has pre-installed PHPUnit via Composer. You can run it instead. In my case, vendor/bin/phpunit works fine. For the rest of the tutorial, I will use vendor/bin/phpunit.

Tests

By completing the previous step, you confirm the seeding and unit test are working well. It is the green light to create the real tests.

1# tests/Feature/UserTest.php
2public function test_follows()
3{
4 $userA = User::find(2);
5 $userB = User::find(3);
6
7 $userA->follows($userB);
8
9 $this->assertEquals(2, $userA->following()->count());
10}
11
12public function test_unfollows()
13{
14 $userA = User::find(3);
15 $userB = User::find(2);
16
17 $userA->unfollows($userB);
18
19 $this->assertEquals(0, $userA->following()->count());
20}
21
22public function test_A_follows_B_and_C()
23{
24 $userA = User::find(1);
25
26 $ids = collect([2, 3, 4, 5, 6, 7, 8, 9, 10]);
27 $random_ids = $ids->random(2);
28
29 $userB = User::find($random_ids->pop());
30 $userC = User::find($random_ids->pop());
31
32 $userA->follows($userB);
33 $userA->follows($userC);
34
35 $this->assertEquals(2, $userA->following()->count());
36}

Run PHPUnit again.

1vendor\bin\phpunit
2PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
3...... 6 / 6 (100%)
4Time: 1.23 seconds, Memory: 10.00MB
5OK (6 tests, 6 assertions)

All tests passed! Cool! I suggest you run the test again to test the consistency.

1vendor\bin\phpunit
2PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
3..F.F. 6 / 6 (100%)
4Time: 1.25 seconds, Memory: 10.00MB
5There were 2 failures:
61) Tests\Feature\UserTest::test_follows
7Failed asserting that 3 matches expected 2.
8C:\xampp\htdocs\TestWithSeed\tests\Feature\UserTest.php:26
92) Tests\Feature\UserTest::test_A_follows_B_and_C
10Failed asserting that 4 matches expected 2.
11C:\xampp\htdocs\TestWithSeed\tests\Feature\UserTest.php:52
12
13FAILURES!
14Tests: 6, Assertions: 6, Failures: 2.

Oops! Two tests failed. What’s going on?

When you run the test for the first time, the tests have made changes to the data in the database. So, when you run the test again, the changed data affects the test result.

That doesn’t mean the application has an error. It is the test case’s responsibility to handle this situation. I would suggest resetting the database before every test run.

Reset the Database

Suggestion one, run a migration refresh and seed before PHPUnit.

1php artisan migrate:refresh --seed
2vendor\bin\phpunit

A better suggestion is to use Traits. Laravel provides two approaches to resetting your database after every test. They are DatabaseMigrations and DatabaseTransactions.

Let’s try the DatabaseMigrations.

1# tests/Feature/UserTest.php
2class UserTest extends TestCase
3{
4 use DatabaseTransactions;
5
6 ...
7}

Run the test.

1vendor\bin\phpunit
2PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
3
4..EEE. 6 / 6 (100%)
5
6Time: 5.53 seconds, Memory: 12.00MB
7
8There were 3 errors:
9
101) Tests\Feature\UserTest::test_follows
11Error: Call to a member function follows() on null
12
13C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:25
14
152) Tests\Feature\UserTest::test_unfollows
16Error: Call to a member function unfollows() on null
17
18C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:35
19
203) Tests\Feature\UserTest::test_A_follows_B_and_C
21Error: Call to a member function follows() on null
22
23C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:50
24
25ERRORS!
26Tests: 6, Assertions: 3, Errors: 3.

It’s not good. The migration is working, but the seeding is not calling on the DatabaseMigrations.

Never mind; let’s give DatabaseTransactions a shot.

1# tests/Feature/UserTest.php
2class UserTest extends TestCase
3{
4 use DatabaseTransactions;
5
6 ...
7}

Run the test again.

1vendor\bin\phpunit
2PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
3
4...... 6 / 6 (100%)
5
6Time: 7.29 seconds, Memory: 14.00MB
7
8OK (6 tests, 6 assertions)

Everything is fine! DatabaseTransactions Trait wraps the queries of each test into a transaction, so data from the previous test doesn’t interfere with subsequent tests.

Conclusion

Seeding your database with planned test data can simulate many different situations and load large amounts of data with little effort.

Less is more. Achieve a better result with less effort.

You can use the sample project from here.

Filed in:

Sky Chin

Sky is the author of Rebuild Twitter with Laravel in Medium and the owner of iteachyouhowtocode.com