【问题标题】:Laravel DatabaseTransactions for PHPunit have no effectPHPunit 的 Laravel DatabaseTransactions 无效
【发布时间】: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


    【解决方案1】:

    问题是我们在 config > 数据库中定义了多个数据库连接。

    database.php conf 文件中,我使用设置中定义的名称更改了与正确数据库的默认连接:

    $connection = 'counterpoint';
    

    DatabaseTransactions 现在可以使用了。

    此解决方案的下一步是将每个测试的连接定向到适当的数据库,而不是更改全局连接。

    【讨论】:

    • 关于下一步,您可以通过使用包含连接名称的数组声明类属性 connectionsToTransact 来定义 Trait 应使用哪些连接。
    猜你喜欢
    • 2016-02-08
    • 2019-11-17
    • 1970-01-01
    • 2016-03-13
    • 2019-11-20
    • 2017-10-11
    • 1970-01-01
    • 2016-10-09
    • 2021-08-29
    相关资源
    最近更新 更多