Symfony 3.3 service mocks for functional tests

天大地大妈咪最大 提交于 2020-01-01 08:51:49

问题


Before Symfony 3.3 it was allowed to set a mocked service onto the container. Now with 3.3 a deprecation warning is thrown because the service is already pre-defined.

What is the new standard way to overwrite an existing or pre-defined service in the container to set a mocked service for a functional test?

E.g. in our case we set a new entity manager with a new mocked connection pointing to a cloned database for testing.

$container->set('doctrine.orm.entity_manager', $testEm);

Setting the "doctrine.orm.entity_manager" pre-defined service is deprecated since Symfony 3.3 and won't be supported anymore in Symfony 4.0.


回答1:


I had the very same problem just a few days ago and I wrote a library to trick Symfony's DIC: https://github.com/TiMESPLiNTER/proxy-mock

The idea is to override the service in the config_test.yml with a "proxy" from the original service class which redirects all the calls to a mock which then can be set dynamically in the test case.

# config_test.yml
services:
    timesplinter.proxy_mock.factory:
        class: timesplinter\ProxyMock\ProxyMockFactory

    acme.api.client:
        factory: 'timesplinter.proxy_mock.factory:create'
        arguments: ['Acme\AppBunde\Services\ApiClient']

This will override the service defined in the original service.(xml|yml) with a proxy of it.

In the test case you can then do something like this:

// Your container aware test case (this exmaple is for PHPUnit)
$mock = $this->getMockBuilder(ApiClient::class)->disableOriginalConstructor()->getMock();

$container->set('acme.api.client')->setMock($mock);

With this your test will run against the mock you provide using the setMock() method.

The library is very new so some feature may be missing. If you use it and miss something please provide a pull request with the desired feature.



来源:https://stackoverflow.com/questions/44323072/symfony-3-3-service-mocks-for-functional-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!