我正在学习一个 Laracast 教程,该教程建议我将语句use DatabaseTransactions;
在我的测试类定义中,以允许我的测试用例中的数据更改将仅在该情况下持续存在。我有一个测试课,
Class MyClassTest extends TestCase
{
// This use statement is responsible for
//all the data operations to persists only with in that test case
use DatabaseTransactions;
/**
* @test
*/
public function my_test_function()
{
// My test case code. Which inserts/updates
//data and assert statement.
}
}
use DatabaseTransactions
的工作方式是,方法中的数据更改仅在该方法中保留。这究竟是如何运作的?
如前所述,DatabaseTransactions
是 trait,它包含带有@before
注释的方法beginDatabaseTransaction
。
- 在测试类中具有
use DatabaseTransactions
可以让类具有该方法。 - 由于方法
beginDatabaseTransaction
包含@before
注释,因此它将在每个测试用例之前执行。
下面是在测试用例完成之前 开始事务并回滚现有事务的方法定义(目前还不清楚为什么应该在测试用例完成之前调用
@before
(。@before
公共函数开始数据库事务(({
$this->app->make('db')->beginTransaction(); $this->beforeApplicationDestroyed(function () { $this->app->make('db')->rollBack(); });
}