5
votes

I am trying to migrate my Symfony 3.4 app to Symfony 4.1.

The tests are not working because the services are by default private (and it's a good news).

Following this post: https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing, I am still facing the issue of private service :

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The "my.service" 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.

In the following compiler pass, my private service was not found in the $definitions : vendor/symfony/framework-bundle/DependencyInjection/Compiler/TestServiceContainerRealRefPass.php

What should be the problem?

UPDATED

Here the definition :

    <service id="my.service"
             class="My\Bundle\GreatService">
        <argument type="service" id="doctrine.orm.entity_manager" />
    </service>

UPDATED (again)

Here the Unit test

<?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');
    }
//...
}
1
Welcome to Stack Overflow. Please add the relevant parts of your service.yml to your question, so that we can see the information needed to answer your question. Also, you should add the function of the controller which fails, if it is a specific one.KhorneHoly
are you trying to inject this service somewhere else ? If so you just have to declare it public : symfony.com/doc/current/service_container/… (just set the public to true)Snroki
no, the service should stay private and we used this service by dependency injection. Not using the container. We used the container only on unit test. For that I followed the post : symfony.com/blog/new-in-symfony-4-1-simpler-service-testingMohammed Mehira
A PHPUnit Mock should be enough. If you really need the service, there is something wrong with your architecture.fxbt
It's actually an interesting problem. Some discussion here. A compiler pass for testing which sets everything to public might be the best bet.Cerad

1 Answers

2
votes

That's strange that code above doesn't work. When I used symfony 4.0 I used such trick:

1.Add services_test.yaml in config folder with following content:

services:
  _defaults:
    public: true

  test.my.service: "@my.service"

2.Now you can get service from your container:

$this->myService = self::$container->get('test.my.service')

BTW do you inject this service somewhere, because unused services are removed by default (if they are not public or synthetic).