php - 如何在 Symfony 5.3 phpunit 测试中访问私有服务?
问题描述
我想为我的 Symfony 5.3 应用程序的 phpunit-tests 定义一个功能测试用例,该应用程序需要security.password_hasher
来自容器的私有服务。
我得到以下异常
App\Tests\Functional\SiteResourceTest::testCreateSite
Symfony\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);
}
}
解决方案
我通过在以下位置明确公开服务来解决它services_test.yaml
:
services:
Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher:
public: true
然后通过其类名检索服务
$this->passwordHasher = $container->get(UserPasswordHasher::class);
推荐阅读
- mysql - MariaDB 中 where 子句中的 if 条件
- machine-learning - 我为 Keras 中任何优化器的衰减参数设置什么值
- angular - 如何按字段名称查询 Firestore 并使用 Angular 在 ionic 4 列表中生成数据
- html - 将 primeNG p-dropdown 宽度设置为 min-content
- python-3.x - 为什么以下在 chrome webdriver 中可以正常工作,但在 firefox webdriver 中“超出视口范围”?
- amazon-web-services - 我们如何使用 cloudfront 故障转移到另一个自定义源 - 我的两个源都是 ALB
- mysql - 一列的MySQL SUM,只取一个相同的字段
- r - 如何在 x 轴上绘制年份,在 y 轴上绘制三个连续变量并重复 32 个因子?
- json - 如何将存储在s3中的地图作为文件读取为spark中的json?
- swift - SwiftUI - “[Color]”类型的值没有“已识别”成员