【问题标题】:Testing in Laravel, setUp & tearDown doesn't rollBack my database transaction?在 Laravel 中进行测试,setUp 和 tearDown 不会回滚我的数据库事务?
【发布时间】:2014-01-24 15:55:46
【问题描述】:

我在 Laravel 测试中遇到了这种奇怪的行为。让我告诉你我的测试。

<?php 
class MatchesControllerTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        DB::beginTransaction();
    }

    public function tearDown()
    {
        DB::rollBack();

    }

     public function testForFun()
    {
             $title = 'Yay Great Post';
        // "Create" post
        Post::create(compact('title'));
             $crawler = $this->client->request('GET', 'posts');

        $this->assertEquals(
            1,
            count($crawler->filter("body:contains('{$title}')")),
            "Expected to see the text '{$title}' within a body element."
        );
    }
}

现在理想情况下,测试应该创建一行并在测试结束后立即删除,但它没有发生,我应该做些什么。我知道当发生一些意外异常时会调用回滚,但我故意在最后调用它,这不应该像我们认为的那样工作吗?

【问题讨论】:

  • 是否调用了rollBack() 方法? Post::create() 不会调用它自己的commit() 吗?
  • 我遇到了同样的问题。据我所知::create() 没有使用交易。即便如此,Laravel 也支持嵌套事务。
  • 哦,这就是为什么它不能像我们预期的那样工作!
  • 尝试调用 parent::tearDown();在tearDown方法上,在你回滚之前
  • @KbirMhrjn Post::create() 也将模型保存到数据库中。 create() 函数在 Illuminate\Database\Eloquent\Builder 中并调用$instance-&gt;save(); 方法。

标签: php unit-testing laravel-4


【解决方案1】:

至少在 Laravel 5 中,您可以添加 DatabaseMigrations trait:

use Illuminate\Foundation\Testing\DatabaseMigrations;

class MatchesControllerTest extends TestCase {
    use DatabaseMigrations;

    public function testForFun() { 
       // your test.. 
    }
}

该特征创建和删除您在migrations 中定义的数据库表,只是为了您的测试。 Laravel testing documentation 中有关该特征的更多信息

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 2018-07-21
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2011-05-24
    相关资源
    最近更新 更多