首页 > 解决方案 > 如何在 Symfony 5.3 phpunit 测试中访问私有服务?

问题描述

我想为我的 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);
    }
}

标签: phpsymfonysymfony5

解决方案


我通过在以下位置明确公开服务来解决它services_test.yaml

services:
    Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher:
        public: true

然后通过其类名检索服务

$this->passwordHasher = $container->get(UserPasswordHasher::class);

推荐阅读