【问题标题】:DatabaseTransactions after each test每次测试后的 DatabaseTransactions
【发布时间】:2017-06-05 20:33:14
【问题描述】:

我正在尝试使用 DatabaseTransactions 特征测试我的 Laravel 系统。问题是它只有在对 TestCase 的所有测试都运行之后才回滚事务。是否可以为 TestCase 中的每个测试创建一个新的数据库实例?

此测试用例有时会返回全绿色,但有时不会。当它在写入时执行测试时,一切正常,但是当顺序颠倒时,第一个失败,因为之前创建了一个潜在客户。我能做什么?

public function testPotentialLeads()
{
    factory(Lead::class)->create(['lead_type' => LeadType::POTENTIAL]);
    factory(Lead::class)->create();
    factory(Lead::class)->create();

    $potential_leads = Lead::potentials()->get();

    $this->assertEquals(1, $potential_leads->count());
    $this->assertEquals(3, Lead::all()->count());
}

public function testAnotherLeadFunction()
{
    $lead = factory(Lead::class)->create();

    $this->assertTrue(true);
}

【问题讨论】:

  • 你可以使用setUp()方法。

标签: php laravel phpunit


【解决方案1】:

我发现了我的错误。它失败了,因为当我这样做时:

factory(Lead::class)->create(['lead_type' => LeadType::POTENTIAL]);
factory(Lead::class)->create();
factory(Lead::class)->create();

$potential_leads = Lead::potentials()->get();

$this->assertEquals(1, $potential_leads->count());
$this->assertEquals(3, Lead::all()->count());

随机生成了两条线索类型(通过模型工厂),因此在创建更多潜在线索时进行了一些尝试。

【讨论】:

    【解决方案2】:
    1. 首先,这个测试并不是真正的测试:$this->assertTrue(true);。如果您想测试是否创建了潜在客户,您应该使用 $this->assertTrue($lead->exists());

    2. 如果要按一定顺序运行单元测试,可以使用@depends注解

    3. DatabaseTransactions trait 会在每次测试后回滚,而不是在所有测试后回滚

    4. 如果您想在每次测试之前和之后迁移和迁移回滚而不是将它们包装到事务中,您可能需要使用 DatabaseMigrations 特征

    5. 如果您想使用自定义设置和拆卸方法,请改用afterApplicationCreatedbeforeApplicationDestroyed 方法来注册回调

    【讨论】:

    • 1.我知道。我写了一个虚拟测试只是为了看看会发生什么。 3. 那么为什么测试有时返回 true 有时返回 false?
    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2021-04-14
    • 2023-04-02
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多