【发布时间】:2017-09-18 21:12:02
【问题描述】:
为现有 API 编写测试,有很多情况下数据库已被修改。我一直在做的事情如下:
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 trait 应该会为你重置一切。但是,当我使用它时,我仍然在数据库中找到测试创建的记录。
以下是我的使用方法:
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 正常工作将节省大量时间,并使其他人更容易阅读睾丸。
【问题讨论】:
标签: laravel unit-testing testing phpunit