【问题标题】:Seed once several tables for phpunit I testing with Laravel 5.4为我用 Laravel 5.4 测试的 phpunit 播种几个表
【发布时间】:2018-01-30 00:54:06
【问题描述】:

我正在使用内存中的 sqlite 编写功能测试以获得更快的结果。

一切似乎都很好,但我有几个表需要填写,以便测试正常工作。它们是小表,几乎从不改变,所以我只想在 phpunit 命令的开头播种一次。

有可能吗???

我唯一努力的就是添加:Artisan::call('db:seed');createApplication() 但这会为每次测试播种一次,我不需要它..

知道我应该怎么做吗?

【问题讨论】:

  • 您是否尝试过创建一个虚拟测试来调用 artisan::call('db:seed') 并将其命名为作为第一个测试运行?
  • 它可能会起作用,但做这种事情并不是那么好......
  • 您的方法不是最好的,因为一个测试可能会以一种会破坏未来测试的方式操纵数据,或者使测试相互依赖。正确的做法是插入每个测试使用的数据。
  • 是的,您可能是对的,但是在这种情况下,依赖关系非常简单,这应该可以为我的测试节省大量时间。

标签: php laravel testing phpunit


【解决方案1】:

您可以随时使用环境变量来刷新数据库。我不知道这是否是最好的方法,但它对我有用。

将变量添加到 .env 文件

DB_REFRESH=true

并更改 CeatesApplication.php trait 方法:

   public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        if(getenv('DB_REFRESH') === 'true') {
            \Artisan::call('migrate:refresh');
            \Artisan::call('db:seed');
            putenv('DB_REFRESH=false');
        }

        return $app;
    }

然后在 ExampleTest.php

中尝试
public function testBasicTest()
{
    $this->assertTrue(true);
}

public function testChangeDatabase()
{
    //if database changes here set variable to true
    //and it will be refreshed before the next test
    putenv("DB_REFRESH=true");
}

public function testRefresh()
{
    //you have fresh database here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2018-01-21
    • 2017-07-28
    • 2017-09-09
    • 2017-11-10
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多