Search code examples
phpsymfonysymfony5

How to access a private service in Symfony 5.3 phpunit tests?


I want to define a functional testcase for my phpunit-tests for my Symfony 5.3 application which requires the private service security.password_hasher from the container.

I get the following execption

  1. App\Tests\Functional\SiteResourceTest::testCreateSite Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The security.password_hasher service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.

I followed the instructions from the documentation about retrieving services in the test

What am i doing wrong? How can i fix this?

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);
    }
}

Solution

  • I solved it by making the service explicitly public in the services_test.yaml:

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

    And then retrieving the service by its classname

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