Answer the question
In order to leave comments, you need to log in
How to create a service in symfony, whose dependency is determined by the environment?
When executing unit tests (env=test), I would like to get a tested service from the service container, which was "cooked" with a "fake" dependency. Which particular class to use as a dependency should be determined depending on the env.
For example:
MyService
{
private $dependency;
public function __constructor(DependencyInterface $dependency)
{
$this->dependency = $dependency;
}
public function getDependency(): DependencyInterface
{
return $this->dependency;
}
}
RealDependency implement DependencyInterface{}
FakeDependency implement DependencyInterface{}
MyServiceTest extends KernelTestCase
{
public function testAction()
{
$kernel = self::bootKernel();
$service = $kernel->getContainer()->get('app.my_service');
$this->assertInstanceOf(FakeDependency::class, $service->getDependency());
}
}
Answer the question
In order to leave comments, you need to log in
If the dependency is on APP_ENV, then it's easier like this
# config/services.yaml
services:
DependencyInterface: '@RealDependency'
# config/services_test.yaml
services:
DependencyInterface: '@FakeDependency'
You can use expressions: https://symfony.com/doc/current/service_container/...
Or you can see how Symfony services are substituted depending on the environment (EventDispatcher, container, etc).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question