2017-04-21 63 views
1

爲現有API編寫測試,有很多情況下數據庫已被修改。我一直在做的東西如下:針對PHPunit的Laravel DatabaseTransaction沒有任何效果

public function testPut() 
{ 
    //setup 
    /*Copy an existing record and take its data as an array. 
    * the function being tested will take an array of data 
    * and create a new record. Using existing data guarantees 
    * the data is valid. 
    */ 

    $customerObj = Customer::getInstance(); //regular instantiation disabled in this api 
    $cust = ArCust::first()->toArray(); 
    $oldNum = $cust['CUST_NO']; 
    unset($cust['CUST_NO']); 
    $custNo = rand(1, 9999999999999); 


    //test 
    /*put() creates a new customer record in the database 
     and returns the object. 
    */ 

    $this->assertInternalType('object', $customerObj->put($custNo, $cust)); 


    //cleanup 
    /*manually remove the newly created record. 
    */ 
    ArCust::whereNam($cust['NAM'])->whereNotIn('CUST_NO', [$oldNum])->delete(); 
} 

我現在運行到實例,其中API創建或更新基於外鍵許多表。要花費太多時間才能完成並手動重置每個表格。

Laravel提供的DatabaseTransaction特性應該是爲您重新設置所有功能。但是,當我使用它時,我仍然可以在數據庫中找到測試創建的記錄。 這裏是我如何使用它:

class CustomerTest extends TestCase 
{ 
    use DatabaseTransactions; 

    public function testPut() 
    { 
     //setup 
     $customerObj = Customer::getInstance(); 
     $cust = ArCust::first()->toArray(); 
     $oldNum = $cust['CUST_NO']; 
     unset($cust['CUST_NO']); 
     $custNo = rand(1, 9999999999999); 


     //test 
     $this->assertInternalType('object', $customerObj->put($custNo, $cust)); 

    } 
} 

我使用這個不正確嗎?讓DatabaseTransactions正常工作將節省大量的時間,並使睾丸對其他人更易讀。

回答

0

從您的測試看起來好像你不打電話beginDatabaseTransaction()

你有沒有試過類似的東西?

class CustomerTest extends TestCase 
{ 
    use DatabaseTransactions; 

    public function setUp() 
    { 
     parent::setUp(); 

     $this->beginDatabaseTransaction(); 
    } 

    public function testPut() 
    { 
     $customerObj = Customer::getInstance(); 
     $cust = ArCust::first()->toArray(); 
     $oldNum = $cust['CUST_NO']; 
     unset($cust['CUST_NO']); 
     $custNo = rand(1, 9999999999999); 

     $this->assertInternalType('object', $customerObj->put($custNo, $cust)); 
    } 
} 
+0

我沒有嘗試這個,但確實弄清楚了什麼是錯誤的,並且發佈了它作爲答案。 – Naltroc

0

問題是我們在config> database中定義了多個數據庫連接。

database.php的conf文件,我改變了默認連接到使用其名稱正確的數據庫如設置定義:

$connection = 'counterpoint'; 

DatabaseTransactions現在的作品。

該解決方案的下一步是將每個測試的連接指向適當的數據庫,而不是更改全局連接。

+0

關於下一步,您可以通過聲明一個包含連接名稱的數組的屬性'connectionsToTransact'來定義Trait應該使用哪些連接。 – dbrumann

相關問題