如何在 Symfony 5.3 phpunit 测试中访问私有服务?

Rom*_*man 5 php symfony symfony5

我想为我的 Symfony 5.3 应用程序的 phpunit-tests 定义一个功能测试用例,它需要security.password_hasher容器的私有服务。

我收到以下异常

  1. App\Tests\Functional\SiteResourceTest::testCreateSite Symfony\Component\DependencyInjection\Exception\ServiceNotFoundExceptionsecurity.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Rom*_*man 2

我通过在以下位置明确公开该服务来解决这个问题services_test.yaml

services:
    Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher:
        public: true
Run Code Online (Sandbox Code Playgroud)

然后通过类名检索服务

$this->passwordHasher = $container->get(UserPasswordHasher::class);
Run Code Online (Sandbox Code Playgroud)