我想为我的Symfony 5.3应用程序中的phpunit测试定义一个功能测试用例,该用例需要容器中的私有服务
我收到以下异常:
我做错了什么? 我怎样才能修复这个问题?
security.password_hasher
。我收到以下异常:
我按照文档中关于在测试中检索服务的说明操作。
App\Tests\Functional\SiteResourceTest::testCreateSite
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: 当容器被编译时,security.password_hasher
服务或别名已被删除或内联。您应该使其公开,或停止直接使用容器并改用依赖注入。
我做错了什么? 我怎样才能修复这个问题?
class CustomApiTestCase extends ApiTestCase
{
protected UserPasswordHasher $passwordHasher;
protected function setUp(): void
{
// (1) boot the Symfony kernel
self::bootKernel();
// (2) use static::getContainer() to access the service container
$container = static::getContainer();
// (3) run some service & test the result
$this->passwordHasher = $container->get('security.password_hasher');
}
protected function createUser(
string $email,
string $password,
): User {
$user = new User();
$user->setEmail($email);
$encoded = $this->passwordHasher->hash($password);
$user->setPassword($encoded);
$em = self::getContainer()->get('doctrine')->getManager();
$em->persist($user);
$em->flush();
return $user;
}
protected function createUserAndLogIn(Client $client, string $email, string $password): User
{
$user = $this->createUser($email, $password);
$this->logIn($client, $email, $password);
return $user;
}
protected function logIn(Client $client, string $email, string $password)
{
$client->request('POST', '/login', [
'headers' => ['Content-Type' => 'application/json'],
'json' => [
'email' => $email,
'password' => $password
],
]);
$this->assertResponseStatusCodeSame(204);
}
}