爲現有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
正常工作將節省大量的時間,並使睾丸對其他人更易讀。
我沒有嘗試這個,但確實弄清楚了什麼是錯誤的,並且發佈了它作爲答案。 – Naltroc