【问题标题】:Laravel 5 Testing with phpUnit without reset my databaseLaravel 5 使用 phpUnit 进行测试而不重置我的数据库
【发布时间】:2017-04-02 22:10:15
【问题描述】:

有没有办法让 setUp() 和 tearDown() 方法告诉 laravel “在数据库中进行所有这些插入,但是当你完成所有测试时,删除所有插入而不重置数据库”

我需要做这样的测试:

/** @test */
public function testRegistration(){

   $account = [
    'name'     => 'test',
    'email'    => 'test@gmail.com',
    'password' => '123451234'
    ];

    $this->visit('/register')
         ->type($account['name'],'name')
         ->type($account['email'],'email')
         ->type($account['password'],'password')
         ->type($account['password'],'password_confirmation')
         ->press('Register')
         ->seePageIs('/home');
}

首先,我可以运行phpunit,它会工作,如果我再次运行,当然它会返回一个错误,告诉我我不能使用这封电子邮件,因为已经在数据库中。

问题是我不能简单地重置我的数据库,我已经在我的数据库中插入了 12.000 行并且我无法创建 test_database 因为我需要插入到我的应用程序中的这 12.000 行是有意义的。

我没有找到任何我可以使用的信息,我能找到的只是“让你的测试调用 migration::refresh 并发送 4 分钟以再次填充你的表”,但我确信这是可能的找到更好的解决方案!

另外,我应该把我的 setUp() 方法放在哪里,我在哪里调用它?

谢谢。

【问题讨论】:

    标签: database unit-testing laravel-5 phpunit laravel-migrations


    【解决方案1】:

    参见this 和这个documentation(处理事务)。

    此 trait 只会将默认数据库连接包装在事务中。

    换句话说,插入将是“伪造的”,因此您无需每次都将其删除。

    另一种选择是添加另一个测试,在该测试中删除您所做的每个插入。

    User::where('name', 'test')->where('email','test@gmail.com')->delete();
    

    【讨论】:

    • 谢谢,正是我需要的!
    猜你喜欢
    • 2015-05-07
    • 2011-06-02
    • 2016-06-04
    • 2014-08-02
    • 2016-05-15
    • 2014-12-19
    • 2017-09-29
    • 2015-01-27
    • 2011-05-14
    相关资源
    最近更新 更多