2017-01-20 21 views
0

我正在尝试使用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); 
} 
+0

你可以使用'setUp()'方法。 – yivi

回答

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两根导线(通过模型厂),因此有当被创造更多的潜在客户一些尝试。

1
  1. 首先,本次测试的心不是一个真正的考验:$this->assertTrue(true);。如果你想测试线是否被创造了,你应该使用,$this->assertTrue($lead->exists());

  2. 如果你想以某种顺序运行单元测试,你可以使用@depends注释

  3. DatabaseTransactions特质确实回滚每次测试后,不单所有测试

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

  5. 如果你想使用自定义安装和拆卸方法,使用afterApplicationCreatedbeforeApplicationDestroyed方法,而不是注册回调

+0

1.我知道。我写了一个虚拟测试来看看会发生什么。那么为什么测试有时会返回真实并且有时是错误的呢? – Alan