Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
You should either make it public, or stop using the container directly and use dependency injection instead
metrag.api.service.realty:
class: ...
public: true
$container->get(RealtyService::class)
Why do you need a container? Create a service for yourself using new, mock its dependencies.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question