每次测试后的DatabaseTransactions

时间:2017-01-20 19:01:40

标签: php laravel phpunit

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

此测试用例有时会返回所有绿色,但有时不返回。当它执行测试时,一切正常,但是当订单被颠倒时,第一个失败,因为之前创建了一个Lead。我该怎么办?

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);
}

2 个答案:

答案 0 :(得分:2)

  1. 首先,这个测试不是真正的测试:$this->assertTrue(true);。如果您想测试是否已创建潜在客户,则应使用$this->assertTrue($lead->exists());

  2. 如果您想按特定顺序运行单元测试,可以使用@depends注释

  3. DatabaseTransactions特征在每次测试后都会回滚,而不是在所有测试之后回滚

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

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

答案 1 :(得分:0)

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

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());

使用随机LeadType(通过模型工厂)生成两个潜在客户,因此在创建更多潜在潜在客户时会有一些尝试。

相关问题