Notes for laravel using database test

Time:2021-1-23

Compared with other tests, database testing can be said to be relatively complex and cumbersome, because database testing will inevitably involve the addition, deletion, modification and query of the database, and these operations will affect the data of the database, and the most taboo of our testing is to modify the data of the test, because in this way, the next test, the test results may change.

Fortunately, laravel provides us with a very simple database testing method, and will not affect the original data.

use DatabaseMigrations

By using the transfer table, we can modify the data. However, this requires that our data be obtained throughmigrationIf we create it directly in the database, we will prompt when we test it:

SQLSTATE[HY000]: General error: 1 no such table: exchange_code

We can take a look at the source code of database migrations. We can see that it is a trait, which will be executed before the test

migrate:fresh

After performing the test

migrate:rollback

In this way, we can ensure that all our operations on the database will be rolled back.

matters needing attention

theremigrate:fresh All tables are deleted and the data is rebuilt

use RefreshDatabase

This way back to determine whether it is memory data test, if so, because it is in memory operation, does not affect the database.

If it is a database such as mysql, it will enable transactions, that is, the data we test will not really be submitted. After the test, we roll back and then submit, which is equivalent to doing nothing to the database.

When testing the database, we use the factory to create data, otherwise you will find that even if the database has data, it is empty.


public function testGet()
 {
  factory(Exchange::class)->create();

  $exchange = Exchange::select('code')->where('status', 0)->first();
  $code = $exchange->code;

  $this->assertDatabaseHas('exchange_code', [
   'code' => $code,
  ]);
 }

summary

This article about the use of laravel database testing notes introduced here, more related to laravel database testing content, please search the previous article of developer or continue to browse the following related articles, hope you can support developer more in the future!