我正在尝试将我的 Symfony 3.4 应用程序迁移到 Symfony 4.1。
测试不起作用,因为服务默认是私有(private)的(这是个好消息)。
关注这篇文章:https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing , 我还是面临私服的问题:
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:编译容器时“my.service”服务或别名已被删除或内联。您应该将其公开,或者停止直接使用容器并改为使用依赖注入(inject)。
在下面的编译过程中,我的私有(private)服务没有在$definitions
中找到:vendor/symfony/framework-bundle/DependencyInjection/Compiler/TestServiceContainerRealRefPass.php
应该是什么问题?
已更新
这里是定义:
<service id="my.service"
class="My\Bundle\GreatService">
<argument type="service" id="doctrine.orm.entity_manager" />
</service>
已更新(再次)
这里是单元测试
<?php
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class MyServiceTest extends KernelTestCase
{
protected $myService;
public function setUp()
{
self::bootKernel();
$this->myService = self::$container->get('my.service');
}
//...
}
最佳答案
奇怪的是上面的代码不起作用。当我使用 symfony 4.0 时,我使用了这样的技巧:
1.在config
文件夹中添加services_test.yaml
,内容如下:
services:
_defaults:
public: true
test.my.service: "@my.service"
2.现在你可以从你的容器中获取服务了:
$this->myService = self::$container->get('test.my.service')
顺便说一下,您是否在某处注入(inject)了此服务,因为默认情况下会删除未使用的服务(如果它们不是公共(public)的或合成的)。
关于php - 私有(private)服务和 Symfony 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51377317/