gpt4 book ai didi

php - 如何在 Symfony 5.3 phpunit 测试中访问私有(private)服务?

转载 作者:行者123 更新时间:2023-12-05 09:31:20 29 4
gpt4 key购买 nike

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

我得到以下异常

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

我按照有关 retrieving services in the test 的文档中的说明进行操作

我做错了什么?我该如何解决这个问题?

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

最佳答案

我不得不重写服务的完整定义以防止在缓存编译期间出现以下错误:

The definition for "security.user_password_hasher" has no class. Ifyou intend to inject this service dynamically at runtime, please markit as synthetic=true. If this is an abstract definition solely usedby child definitions, please add abstract=true, otherwise specify aclass to get rid of this error.

services.yaml

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

关于php - 如何在 Symfony 5.3 phpunit 测试中访问私有(private)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68865038/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com