如何在 Symfony 3.4 phpunit 测试中访问私有服务? [英] How to access a private service in Symfony 3.4 phpunit tests?

查看:24
本文介绍了如何在 Symfony 3.4 phpunit 测试中访问私有服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个发送邮件的服务.我已经创建了一个单元测试,但我有一些弃用警告,我想知道它的用途.在我的 setUp() 函数中,我得到了这样的服务

I want to test a service who send mail. I have create a unit test but i have some deprecation warning and i want to know the good use. In my setUp() function i get the service like this

    $this->container = self::$kernel->getContainer();
    $this->swiftMailer = $this->container->get('swiftmailer.mailer');

但是我有这个消息

The "swiftmailer.mailer" service is private, getting it from the container is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead.

最好的做法是什么?我对 security.authentication.manager 有相同的消息

What is the best pratice to do ? I have the same message for security.authentication.manager

推荐答案

服务 在 Symfony 3.4 中默认设为私有.

Symfony 4.1

从 Symfony 4.1 开始 所有私有服务都可用在测试环境中通过一个特殊的测试容器:

Starting with Symfony 4.1 all private services are made available in test environment via a special test container:

class FooTest extends KernelTestCase
{
    static::bootKernel();
    $this->swiftmailer = static::$container->get('swiftmailer.mailer');
}

Symfony 3.4 和 4.0

您可以在 Symfony 3.4 和 4.0 中解决此问题的一种方法是在测试环境中注册一个服务定位器,这将公开您需要在测试中访问的私有服务.

One way you could solve it in Symfony 3.4 and 4.0 is to register a service locator in test environment, that would expose private services you need access to in tests.

另一种方法是简单地为每个私有服务创建一个公共别名您需要在测试中访问.

Another way would be to simply create a public alias for each private service you need access to in tests.

例如:

# app/config/config_test.yml
services:
    test_alias.swiftmailer.mailer:
        alias: '@swiftmailer.mailer'
        public: true

在您的测试中,您现在可以通过公共别名 test_alias.swiftmailer.mailer 访问您的私人服务:

In your test you'll be now able to access your private service via the public alias test_alias.swiftmailer.mailer:

$this->container = self::$kernel->getContainer();
$this->swiftMailer = $this->container->get('test_alias.swiftmailer.mailer');

这篇关于如何在 Symfony 3.4 phpunit 测试中访问私有服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆