条令重述并没有在功能测试中刷新其状态



我正在学习如何为基于Api平台的Api编写测试。我在测试课上使用Alice助手RefreshDatabaseTrait。在文档中,它说这个特性包装了每一个测试都是事务,当它完成时,它就会回滚。因此,例如,当我使用HttpClient删除Employee并想断言它已被删除时,我必须再次初始化EmpoyeeRepository才能通过测试。如果我不这样做,"count(("方法将返回10个Employees。嵌套事务有问题吗?

class EmployeeTest extends AbstractTest
{
use RefreshDatabaseTrait;
/** @test
* @group functional
*/
public function deleteEmployee(): void
{
// Arrange
/** @var EmployeeRepository $employeeRepository */
$employeeRepository = static::getContainer()->get(EmployeeRepository::class);
/** @var Employee $employee */
$employee = $employeeRepository->findOneBy([]);
// Act
$this->createClientWithCredentials()
->request('DELETE', '/employees/' . $employee->getUuid());
// Assert
$employeeRepository = static::getContainer()->get(EmployeeRepository::class);
static::assertResponseIsSuccessful();
static::assertEquals(9, $employeeRepository->count([]));
}
}
class AbstractTest extends ApiTestcase
{
private ?string $token = null;
/**
* @throws JsonException
*/
protected function createClientWithCredentials($token = null): Client
{
$token = $token ?: $this->getToken();
return static::createClient([], ['headers' => ['Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', 'Accept' => 'application/json']]);
}
/**
* Use other credentials if needed.
* @throws JsonException
*/
protected function getToken($body = []): string
{
if ($this->token) {
return $this->token;
}
$response = static::createClient()->request('POST', '/token', ['json' => $body ?:
[
"email" => "admin@email.com",
"password" => "pass"
]
]);
static::assertResponseIsSuccessful();
return json_decode($response->getContent())->token;
}
}

Api平台2.6.8,Symfony 6.0,Hautelok/Alice 2.11条令/orm 2.13.1

您没有说明重新命名EmployeeRepository的原因。如果你不这样做呢?你还让那个老员工回来吗?

在不了解更多细节的情况下,我可能会认为这可能是一个缓存问题。

存储库,或者更具体地说,entitymanager保存了一个缓存,我注意到它有点脆弱。

尝试清除

$employeeRepository->getEm()->clear();,其中getEm是从repo返回EntityManager$_em的自定义函数。

我发现了问题:

public function deleteEmployee(): void
{
// Arrange
//getContrainer is booting Kernel
/** @var EmployeeRepository $employeeRepository */
$employeeRepository = static::getContainer()->get(EmployeeRepository::class);
/** @var Employee $employee */
$employee = $employeeRepository->findOneBy([]);
// Act
// This method boot's another Kernel!
$this->createClientWithCredentials()
->request('DELETE', '/employees/' . $employee->getUuid());
// Assert
$employeeRepository = static::getContainer()->get(EmployeeRepository::class);
static::assertResponseIsSuccessful();
static::assertEquals(9, $employeeRepository->count([]));
}

所以看来您不能多次启动内核。

最新更新