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

查看:91
本文介绍了如何在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 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天全站免登陆