Laravel 5.7中PHP单元测试之间的测试依赖关系

时间:2018-12-13 15:24:53

标签: php laravel phpunit

我正在研究Laravel 5.7,我想问一个关于PHPUnit测试的问题。

我有一个测试类,例如ProductControllerTest.php,它有两个方法testProductSoftDelete()testProductPermanentlyDelete()。我想在testProductPermanentlyDelete()中使用批注@depends,以便首先软删除产品,然后获取产品ID,然后进行永久删除测试。这里的问题是DatabaseTransaction特性在每次测试(方法)执行中都会运行事务。我需要在ProductControllerTest类的所有测试之前启动事务,然后在所有测试结束时回滚事务。你有什么想法?根据我从网上搜索到的内容,一切正常。

public function testProductSoftDelete()
{
   some code

   return $product_id;
}

/**
* @depends testProductSoftDelete
*/
public function testProductPermanentlyDelete($product_id)
{
   code to test permanently deletion of the product with id $product_id.
   There is a business logic behind that needs to soft delete first a 
   product before you permanently delete it.

}

以下内容有意义吗?

    namespace Tests\App\Controllers\Product;

    use Tests\DatabaseTestCase;
    use Tests\TestRequestsTrait;

    /**
     * @group Coverage
     * @group App.Controllers
     * @group App.Controllers.Product
     *
     * Class ProductControllerTest
     *
     * @package Tests\App\Controllers\Product
     */

    class ProductControllerTest extends DatabaseTestCase
    {
        use TestRequestsTrait;

        public function testSoftDelete()
        {
            $response = $this->doProductSoftDelete('9171448');
            $response
                ->assertStatus(200)
                ->assertSeeText('Product sof-deleted successfully');
        }


        public function testUnlink()
        {
            $this->doProductSoftDelete('9171448');
            $response = $this->actingAsSuperAdmin()->delete('/pages/admin/management/product/unlink/9171448');

            $response
                ->assertStatus(200)
                ->assertSeeText('Product unlinked successfully');
        }
    }


    namespace Tests;

    trait TestRequestsTrait
    {
        /**
         * Returns the response
         *
         * @param $product_id
         * @return \Illuminate\Foundation\Testing\TestResponse
         */
        protected function doProductSoftDelete($product_id)
        {
            $response = $this->actingAsSuperAdmin()->delete('/pages/admin/management/product/soft-delete/'.$product_id);
            return $response;
        }

    }

    namespace Tests;

    use Illuminate\Foundation\Testing\DatabaseTransactions;

    abstract class DatabaseTestCase extends TestCase
    {

        use CreatesApplication;
        use DatabaseTransactions;
    }

1 个答案:

答案 0 :(得分:0)

创建一个单独的函数来执行两次相同的行为:

public function testProductSoftDelete()
{
    doSoftDelete();
}

public function testProductPermanentlyDelete()
{
    doSoftDelete();
    doPermanentDelete();
}

您的情况不是测试依赖性的情况,但是您真正想做的是检查是否可以永久删除软删除(或类似的东西)。 在这种情况下,创建依赖关系会增加测试的复杂性。 通常最好从头开始安装测试方案(数据/对象),然后执行逻辑,然后测试实际方案是否是预期的。