如何在功能测试中模拟 Symfony 2 服务? [英] How to mock Symfony 2 service in a functional test?
问题描述
我有 symfony 服务,它在某些方法中使用 redis 连接,但不是在所有方法中.
I have symfony service which uses redis connection in some methods but not in all methods.
class ServiceA
{
private $redis;
public function __construct($redis)
{
$this->redis = $redis;
}
public function getRequest($param1, $param2)
{
$result = $param1+ $param2;
return $request;
}
.. other methods which use $redis connection
}
我正在为仅使用 getRequest 方法(此方法不需要 redis 连接)的代码编写功能测试,但由于构造函数将连接作为参数,当我运行测试时,它尝试连接 redis 服务器.
I am writing functional test for the code which use only getRequest method (this method does not need redis connection) but as the constructor takes the connection as an argument, when I run test it tried to connect redis server.
如何编写完全不使用 redis 连接并忽略原始构造函数的模拟服务.
How can I write mock service which does not use redis connection at all and ignore original constructor.
我正在尝试下面提到的方法,但没有成功.即使我禁用了原始构造函数,它仍然尝试连接 redis.
I am trying approach mentioned below but no success. It still tries to connect redis eventhough I have disabled original constructor.
http://blog.lyrixx.info/2013/04/12/symfony2-how-to-mock-services-during-functional-tests.html
$serviceA = $this->getMockBuilder('ServiceA')
->disableOriginalConstructor()
->getMock();
static::$kernel->getContainer()->set('my_bundle.service.a', $serviceA);
推荐答案
在创建 ServiceA
模拟之后,您需要将它传递给客户端的容器(不是内核的容器,因为客户端对象构建了自己的核心).试试这个:
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.
这篇关于如何在功能测试中模拟 Symfony 2 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!