在为现有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特性应该为您重置所有内容。但是,当我使用它时,我仍然在数据库中找到测试创建的记录。
这是我的用法:

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正常工作将节省大量时间,并使睾丸对其他人更具可读性。

最佳答案

从您的测试看来,您没有在呼叫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));
    }
}

关于laravel - 适用于PHPunit的Laravel DatabaseTransactions无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43549944/

10-10 14:11
查看更多