如何在Laravel 4单元测试中的setupBeforeClass方法中为数据库设置种子? [英] How Do I Seed My Database in the setupBeforeClass Method in a Laravel 4 Unit Test?

查看:62
本文介绍了如何在Laravel 4单元测试中的setupBeforeClass方法中为数据库设置种子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Laravel 4测试类,其中包含一些测试,在运行测试之前,我希望为其播种数据库.使用setup()函数为每个测试重新设定种子的时间太长.但是,当我尝试在静态setupBeforeClass()函数或构造函数中进行播种时,显然不能使用$ this-> seed()方法.

I have a Laravel 4 test class with some tests for which I want to seed my database before running the tests. Using the setup() function to reseed for each test takes far too long. However, when I try seeding in the static setupBeforeClass() function or the constructor, I obviously can't use the $this->seed() method.

但是我都不能使用程序化Artisan命令,因为当我这样做时,会出现以下错误:PHP Fatal error: Class 'Artisan' not found in <test class name>.

But neither can I use programmatic Artisan commands, because when I do, I get the following error: PHP Fatal error: Class 'Artisan' not found in <test class name>.

这是我想用来播种的代码:

Here is the code I'd like to use to seed:

Artisan::call('migrate:refresh');
Artisan::call('db:seed', array('--class'=>'TestSeeder');

请让我知道如何为每个测试 class 而不是为每个测试 case

Please let me know how I can seed my database once per test class rather than per test case

推荐答案

要获得类似效果的即兴"但很干净的恕我直言,方法是在setUp中执行此操作,但只能在中运行一次(类似于setupBeforeClass所做的):

An "improvised" but pretty clean imho way to achieve a similar effect would be to do this in setUp, but have it run only once (similar to what setupBeforeClass does) like this:

use Illuminate\Support\Facades\Artisan;

class ExampleTest extends TestCase {

    protected static $db_inited = false;

    protected static function initDB()
    {
        echo "\n---initDB---\n"; // proof it only runs once per test TestCase class
        Artisan::call('migrate');
        // ...more db init stuff, like seeding etc.
    }

    public function setUp()
    {
        parent::setUp();

        if (!static::$db_inited) {
            static::$db_inited = true;
            static::initDB();
        }
    }

    // ...tests go here...
}

...这是我的解决方案,看起来很简单并且可以正常工作,解决了每次测试运行前播种和重建db结构的性能问题.但是请记住,正确"的测试方法使您最大的信心,即您的测试方法不会以错误隐藏的方式巧妙地相互依存,它是在每次测试之前重新种子化数据库.方法,因此,如果可以承受性能损失(对于我的测试用例,我负担不起,但是ymmv ...),只需将种子代码放入普通的setUp中.

...this is my solution and it seems simple enough and works fine, solving the performance problems of seeding and rebuilding the db structure before every test run. But remember, the "right" way to do testing, that gives you the greatest confidence your tests methods don't get subtly interdependent in bug-hiding ways, is to re-seed your db before every test method, so just put seeding code in plain setUp if you can afford the performance penalty (for my test cases, I couldn't afford it, but ymmv...).

这篇关于如何在Laravel 4单元测试中的setupBeforeClass方法中为数据库设置种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆