gpt4 book ai didi

laravel - 在 Lumen 中进行单元测试时,数据库迁移和事务之间有什么区别?

转载 作者:行者123 更新时间:2023-12-02 04:03:26 24 4
gpt4 key购买 nike

根据 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。

最佳答案

DatabaseMigrations 在运行测试时迁移数据库,然后在测试完成时回滚数据库。

DatabaseTransactions 使用事务。从数据库插入的任何数据都将在测试后回滚。

两者之间的区别是 DatabaseMigrations 使用迁移(迁移数据库迁移,然后在测试后回滚),而 DatabaseTransactions 使用事务(从数据库插入数据)已回滚)

来源:https://mattstauffer.co/blog/better-integration-testing-in-laravel-5.1-databasemigrations-databasetransactions-and-withoutmiddleware

关于laravel - 在 Lumen 中进行单元测试时,数据库迁移和事务之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com