我正在做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;
}发布于 2018-12-13 23:26:43
创建一个单独的函数来执行相同的行为两次:
public function testProductSoftDelete()
{
doSoftDelete();
}
public function testProductPermanentlyDelete()
{
doSoftDelete();
doPermanentDelete();
}你的情况不是测试依赖的情况,但你真正想做的是检查软删除是否可以永久删除(或类似的东西)。在这种情况下,创建依赖项将增加测试的复杂性。通常更好的做法是从头开始安装测试场景(数据/对象),然后执行逻辑,然后测试实际场景是否符合预期。
https://stackoverflow.com/questions/53765082
复制相似问题