How to mock Symfony 2 service in a functional test? How to mock Symfony 2 service in a functional test? symfony symfony

How to mock Symfony 2 service in a functional test?


After you create ServiceA mock, you need to pass it to client's container (not the one from kernel's because client object builds its own kernel). Try this:

$client = self::createClient();$serviceA = $this->getMockBuilder('ServiceA')    ->disableOriginalConstructor()    ->getMock();$client->getContainer()->set('my_bundle.service.a', $serviceA);

Pay attention, that you must inject this mocked service every time you make a request. It's because the client rebuilds kernel between each two requests.


You should not mock your tested class, you should mock the Redis class and inject it.

If Redis isn't used for this test, you need not even configure the mock.

$redis = $this->getMockBuilder('Redis')->disableOriginalConstructor()->getMock();$serviceA = new ServiceA($redis);


There is special tool which takes care of mocked services - https://github.com/ramunasd/symfony-container-mocks

It's easy like that:

$service = static::$kernel->getContainer()->prophesize('my.custom.service');