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

ffx8fchx  于 2023-10-15  发布在  PHP
关注(0)|答案(4)|浏览(106)

我想为Symfony 5.3应用程序的phpunit-tests定义一个功能测试用例,该应用程序需要容器中的私有服务security.password_hasher
我得到以下例外

  1. App\Tests\Functional\SiteResourceTest::testCreateSiteSymfony\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);
    }
}
svdrlsy4

svdrlsy41#

我不得不重写服务的完整定义,以防止在缓存编译期间出现以下错误:
“security.user_password_hasher”的定义没有类。如果你打算在运行时动态注入这个服务,请将其标记为synthetic=true。如果这是一个只由子定义使用的抽象定义,请添加abstract=true,否则指定一个类来消除此错误。
服务.yaml**

security.user_password_hasher:
    class: Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher
    public: true
    arguments:
      [ '@security.password_hasher_factory' ]
vnzz0bqm

vnzz0bqm2#

我通过在services_test.yaml中显式地公开服务来解决它:

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

然后按服务的类名检索服务

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

iswrvxsc3#

为Symfony 6

如果从Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;扩展
你可以像这样获取容器和UserPasswordHasherInterface:
$paswordHasher = static::getContainer()->get(UserPasswordHasherInterface::class);
此外,您还可以获取实体管理器或存储库:

$entityManager = static::getContainer()->get('doctrine')->getManager();

$repository = static::getContainer()->get('doctrine')->getManager()->getRepository(Foo::class);
qojgxg4l

qojgxg4l4#

测试内核还可以执行以下操作:

class PublicService implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if (stripos($id, 'whatEverIWant') === 0) {
                $definition->setPublic(true);
            }
        }
        foreach ($container->getAliases() as $id => $definition) {
            if (stripos($id, 'whatEverIWant') === 0) {
                $definition->setPublic(true);
            }
        }
    }
}

class AppKernel extends BaseKernel
{
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new PublicService(), PassConfig::TYPE_OPTIMIZE);
        parent::build($container);
    }
}

相关问题