2017-01-20 23 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