vendredi 21 avril 2017

Laravel DatabaseTransactions for PHPunit have no effect

Writing tests for an existing API, there are many cases where the database has been modified. What I have been doing is something as follows:

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();
}

I am now running into instances where the API creates or updates many tables based on foreign keys. It would take far too much time to go through and manually reset each table.

The DatabaseTransaction trait provided by Laravel is supposed to take care of resetting everything for you. However, when I use it, I still find the test-created records in the database. Here is how I have used it:

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));

    }
}

Am I using this incorrectly? Getting DatabaseTransactions to work correctly will save an incredible amount of time, as well as make the testes more readable to other people.

Aucun commentaire:

Enregistrer un commentaire