【发布时间】:2019-05-14 20:38:46
【问题描述】:
我正在处理Laravel 5.7,我想问你一个关于 PHPUnit 测试的问题。
我有一个测试类,比如说ProductControllerTest.php,有两个方法testProductSoftDelete() 和testProductPermanentlyDelete()。我想在 testProductPermanentlyDelete() 中使用注释 @depends 以便首先软删除产品,然后获取产品 ID 并继续进行永久删除测试。这里的问题是DatabaseTransaction trait 在每个测试(方法)执行中运行事务。我需要在我的 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;
}
【问题讨论】: