在 Lumen 中进行单元测试时,数据库迁移和事务之间有什么区别?
What is the difference between database migrations and transactions while unit testing in Lumen?
根据 Lumen 5.3 文档:
Using Migrations
One option is to rollback the database after each test and migrate it
before the next test. Lumen provides a simple DatabaseMigrations trait
that will automatically handle this for you. Simply use the trait on
your test class:
<?php
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$this->get('/foo');
}
}
Using Transactions
Another option is to wrap every test case in a database transaction.
Again, Lumen provides a convenient DatabaseTransactions trait that
will automatically handle this:
<?php
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
use DatabaseTransactions;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$this->get('/foo');
}
}
如您所见,解释文本几乎相同,代码示例也完全相同,但特征用法除外。所以我很清楚,区别完全在于框架处理测试的方式。
它们有什么不同之处?您什么时候更喜欢其中之一?
如果一个差异与我使用的数据库驱动程序有关 MYSQL。
SQL 中的事务使您可以回滚 INSERTion,要提交您必须使用 COMMIT 显式执行的插入。
这使您能够在不更改数据库本身的情况下进行单元测试。
迁移也是如此,但它们不会让您控制每一笔交易。
DatabaseMigrations
在您 运行 测试时迁移数据库,然后在测试完成后回滚数据库。
DatabaseTransactions
使用交易。从您的数据库中插入的任何数据都将在测试后回滚。
两者的区别是DatabaseMigrations
使用迁移(迁移你的数据库迁移然后在测试后回滚)而DatabaseTransactions
使用事务(从数据库插入的数据被回滚)
根据 Lumen 5.3 文档:
Using Migrations
One option is to rollback the database after each test and migrate it before the next test. Lumen provides a simple DatabaseMigrations trait that will automatically handle this for you. Simply use the trait on your test class:
<?php use Laravel\Lumen\Testing\DatabaseMigrations; use Laravel\Lumen\Testing\DatabaseTransactions; class ExampleTest extends TestCase { use DatabaseMigrations; /** * A basic functional test example. * * @return void */ public function testBasicExample() { $this->get('/foo'); } }
Using Transactions
Another option is to wrap every test case in a database transaction. Again, Lumen provides a convenient DatabaseTransactions trait that will automatically handle this:
<?php use Laravel\Lumen\Testing\DatabaseMigrations; use Laravel\Lumen\Testing\DatabaseTransactions; class ExampleTest extends TestCase { use DatabaseTransactions; /** * A basic functional test example. * * @return void */ public function testBasicExample() { $this->get('/foo'); } }
如您所见,解释文本几乎相同,代码示例也完全相同,但特征用法除外。所以我很清楚,区别完全在于框架处理测试的方式。
它们有什么不同之处?您什么时候更喜欢其中之一?
如果一个差异与我使用的数据库驱动程序有关 MYSQL。
SQL 中的事务使您可以回滚 INSERTion,要提交您必须使用 COMMIT 显式执行的插入。
这使您能够在不更改数据库本身的情况下进行单元测试。
迁移也是如此,但它们不会让您控制每一笔交易。
DatabaseMigrations
在您 运行 测试时迁移数据库,然后在测试完成后回滚数据库。
DatabaseTransactions
使用交易。从您的数据库中插入的任何数据都将在测试后回滚。
两者的区别是DatabaseMigrations
使用迁移(迁移你的数据库迁移然后在测试后回滚)而DatabaseTransactions
使用事务(从数据库插入的数据被回滚)