用于功能测试的Symfony 3.3服务模拟 [英] Symfony 3.3 service mocks for functional tests

查看:64
本文介绍了用于功能测试的Symfony 3.3服务模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Symfony 3.3之前,允许在容器上设置模拟服务.现在,在3.3版本中,由于该服务已经预先定义,因此会引发弃用警告.

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);

自Symfony 3.3起,不建议设置"doctrine.orm.entity_manager"预定义服务,并且Symfony 4.0将不再支持该服务.

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.

推荐答案

几天前,我遇到了同样的问题,我写了一个库来欺骗Symfony的DIC: https://github.com/TiMESPLiNTER/proxy-mock

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

想法是用原始服务类中的代理"覆盖config_test.yml中的服务,该服务将所有调用重定向到一个模拟,然后可以在测试用例中对其进行动态设置.

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']

这将覆盖原始服务(xml | yml)中定义的服务及其代理.

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);

通过此操作,您的测试将针对您使用setMock()方法提供的模拟进行.

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

该库是一个非常新的库,因此某些功能可能会丢失.如果您使用它而错过了一些东西,请提供具有所需功能的拉取请求.

这篇关于用于功能测试的Symfony 3.3服务模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆