Laravel的documentation建议使用DatabaseMigrations
特征在测试之间迁移和回滚数据库。
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->get('/');
// ...
}
}
然而,我有一些种子数据,我想在我的测试中使用。如果我运行:
php artisan migrate --seed
然后,它可以用于第一个测试,但它无法通过后续测试。这是因为特征回滚迁移,当它再次运行迁移时,它不会为数据库设定种子。如何在迁移过程中运行数据库种子?
发布于 2021-02-22 07:30:48
在Laravel 8中,如果您使用的是RefreshDatabase
特征,则可以使用以下命令从测试用例中调用种子:
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
// Run the DatabaseSeeder...
$this->seed();
// Run a specific seeder...
$this->seed(OrderStatusSeeder::class);
$response = $this->get('/');
// ...
}
}
有关更多信息/示例,请参阅文档:https://laravel.com/docs/8.x/database-testing#running-seeders
发布于 2018-04-15 15:14:47
您所需要做的就是在setUp函数中调用db:seed
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
// seed the database
$this->artisan('db:seed');
// alternatively you can call
// $this->seed();
}
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->get('/');
// ...
}
}
参考:https://laravel.com/docs/5.6/testing#creating-and-running-tests
发布于 2017-02-21 00:52:40
我花了些功夫才弄明白,所以I thought I'd share。
如果你看一下DatabaseMigrations
的源代码,你会发现它有一个由setUp
调用的函数runDatabaseMigrations
,这个函数被runs before every test调用,并注册一个在teardown上运行的回调。
您可以通过为该函数添加别名来对其进行"extend" the trait排序,在原始名称下重新声明一个包含逻辑的新函数(artisan db:seed
),并在其中调用别名。
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends TestCase
{
use DatabaseMigrations {
runDatabaseMigrations as baseRunDatabaseMigrations;
}
/**
* Define hooks to migrate the database before and after each test.
*
* @return void
*/
public function runDatabaseMigrations()
{
$this->baseRunDatabaseMigrations();
$this->artisan('db:seed');
}
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$response = $this->get('/');
// ...
}
}
https://stackoverflow.com/questions/42350138
复制相似问题