Introduction to Seeding Data in Testing

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).

# database/migrations/2014_10_12_000000_create_users_table.php class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); // following table is storing the relationship between users // user_id is following follow_user_id Schema::create('following', function (Blueprint $table) { $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->integer('follow_user_id')->unsigned()->index(); $table->foreign('follow_user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('following'); Schema::dropIfExists('users'); } }

Next, run the migration.

php artisan migrate Migration table created successfully.

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

[Illuminate\Database\QueryException] SQLSTATE[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`)) [PDOException] SQLSTATE[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.

php artisan migrate Migration table created successfully. Migrated: 2014_10_12_000000_create_users_table Migrated: 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.

# app/User.php class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function follows(User $user) { $this->following()->attach($user->id); } public function unfollows(User $user) { $this->following()->detach($user->id); } public function following() { return $this->belongsToMany('App\User', 'following', 'user_id', 'follow_user_id')->withTimestamps(); } public function isFollowing(User $user) { return !is_null($this->following()->where('follow_user_id', $user->id)->first()); } }

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.

php artisan make:seeder UsersTableSeeder

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

# database/seeds/UsersTableSeeder.php use App\User; use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $users = factory(User::class, 10)->create(); } }

Run the artisan command to perform seeding.

php artisan db:seed --class=UsersTableSeeder

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

# database/seeds/UsersTableSeeder.php use App\User; use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $users = factory(User::class, 10)->create(); } }

Run the artisan command to perform seeding.

php artisan db:seed --class=UsersTableSeeder

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

# database/seeds/DatabaseSeeder.php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); } }

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

php 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.

php artisan make:test UserTest

Prerequisite Test

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

# tests/Feature/UserTest.php use App\User; class UserTest extends TestCase { public function test_have_10_users() { $this->assertEquals(10, User::count()); } }

Run PHPUnit.

phpunit

If it doesn’t work, try this.

vendor/bin/phpunit PHPUnit 5.7.17 by Sebastian Bergmann and contributors. ... 3 / 3 (100%) Time: 2.72 seconds, Memory: 12.00MB OK (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.

# tests/Feature/UserTest.php public function test_follows() { $userA = User::find(2); $userB = User::find(3); $userA->follows($userB); $this->assertEquals(2, $userA->following()->count()); } public function test_unfollows() { $userA = User::find(3); $userB = User::find(2); $userA->unfollows($userB); $this->assertEquals(0, $userA->following()->count()); } public function test_A_follows_B_and_C() { $userA = User::find(1); $ids = collect([2, 3, 4, 5, 6, 7, 8, 9, 10]); $random_ids = $ids->random(2); $userB = User::find($random_ids->pop()); $userC = User::find($random_ids->pop()); $userA->follows($userB); $userA->follows($userC); $this->assertEquals(2, $userA->following()->count()); }

Run PHPUnit again.

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

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

vendor\bin\phpunit PHPUnit 5.7.17 by Sebastian Bergmann and contributors. ..F.F. 6 / 6 (100%) Time: 1.25 seconds, Memory: 10.00MB There were 2 failures: 1) Tests\Feature\UserTest::test_follows Failed asserting that 3 matches expected 2. C:\xampp\htdocs\TestWithSeed\tests\Feature\UserTest.php:26 2) Tests\Feature\UserTest::test_A_follows_B_and_C Failed asserting that 4 matches expected 2. C:\xampp\htdocs\TestWithSeed\tests\Feature\UserTest.php:52 FAILURES! Tests: 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.

php artisan migrate:refresh --seed vendor\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.

# tests/Feature/UserTest.php class UserTest extends TestCase { use DatabaseTransactions; ... }

Run the test.

vendor\bin\phpunit PHPUnit 5.7.17 by Sebastian Bergmann and contributors. ..EEE. 6 / 6 (100%) Time: 5.53 seconds, Memory: 12.00MB There were 3 errors: 1) Tests\Feature\UserTest::test_follows Error: Call to a member function follows() on null C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:25 2) Tests\Feature\UserTest::test_unfollows Error: Call to a member function unfollows() on null C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:35 3) Tests\Feature\UserTest::test_A_follows_B_and_C Error: Call to a member function follows() on null C:\xampp\htdocs\seeding-data-in-the-testing\tests\Feature\UserTest.php:50 ERRORS! Tests: 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.

# tests/Feature/UserTest.php class UserTest extends TestCase { use DatabaseTransactions; ... }

Run the test again.

vendor\bin\phpunit PHPUnit 5.7.17 by Sebastian Bergmann and contributors. ...... 6 / 6 (100%) Time: 7.29 seconds, Memory: 14.00MB OK (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.