G
G
gitdev2019-02-07 21:28:45
symfony
gitdev, 2019-02-07 21:28:45

How to test a service in symfony 4?

Can't get service in class for testing. I would like to get with dependencies that are passed to the constructor.
If only this line is left, the test passes:
$this->assertEquals(42, 42);
I tried to get the service through DI, also an error.
In this case it says:
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The "metrag.api.service.realty" 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.

// tests/AppBundle/Util/CalculatorTest.php
namespace Tests\AppBundle\Util;

use App\Metrag\ApiBundle\Services\RealtyService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class RealtyServiceTest extends WebTestCase
{

    public function testGetOnStatus()
    {
        self::bootKernel();

        // gets the special container that allows fetching private services
        $container = self::$container;

        $realtyService = $container->get('metrag.api.service.realty');

        $this->assertEquals(42, 42);
    }
}

ps
This is important because. the service has logic that needs to be tested.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GTRxShock, 2019-02-07
@GTRxShock

You should either make it public, or stop using the container directly and use dependency injection instead

so, after all, everything is written, the service is private by default, and after the container is assembled, all links are cleared
, so set the level to public for it, or tighten it through di
if the first option, then in config/services.yaml
metrag.api.service.realty:
    class: ...
    public: true

here we must already look for reasons elsewhere
ps why not according to the canon? :)$container->get(RealtyService::class)

I
index0h, 2019-02-08
@index0h

Why do you need a container? Create a service for yourself using new, mock its dependencies.

D
Denis, 2019-02-08
@prototype_denis

Your kernel is not in the "test" environment.
Either environment variables are not picked up, or this value is overwritten somewhere.
sf >= 4.1 should be if memory serves

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question