Symfony/PHPUnit模拟服务 [英] Symfony/PHPUnit mock services
问题描述
我正在为带有PHPUnit的Symfony编写功能测试,而我的模拟无法正常工作.我可能会误解了它们的工作原理.
I'm writing functional tests for Symfony w/ PHPUnit, and my mocks aren't working. It's possible I misunderstood how they work though.
在单元测试的setUp()
方法中,我有以下代码:
In my unit test's setUp()
method I have this code:
...
// Create a stub
$stub = $this->getMockBuilder('\\ApiBundle\\Util\\WordPressBridge')
->disableOriginalConstructor()
->getMock();
// Configure the stub.
$user = new WordPressUser();
$user->setUsername('dummy');
$stub->expects($this->any())
->method('checkCredentials')
->will($this->returnValue(true));
$stub->expects($this->any())
->method('getUser')
->will($this->returnValue($user));
...
在我的Symfony应用程序中,我定义了一个服务:
In my Symfony application, I have a service defined:
services:
api.wp_bridge:
class: ApiBundle\Util\WordPressBridge
arguments: [@service_container]
据我了解,该模拟应该替换真正的WordPressBridge
,但这不是正在发生的事情.我的原件仍在使用中.我想念什么吗?
It's my understanding that the mock should be replace the real WordPressBridge
, but that isn't what's happening. My original is still being used. Am I missing something?
推荐答案
据我了解,该模拟应该代替真正的WordPressBridge,但事实并非如此.我的原件仍在使用中.我想念什么吗?
It's my understanding that the mock should be replace the real WordPressBridge, but that isn't what's happening. My original is still being used. Am I missing something?
基本上,您必须以某种方式在Symfony容器中替换服务.
Basically you have to replace your service somehow in the Symfony Container.
如果您进行功能测试",则可能应该为测试" env创建测试虚拟"服务,这将覆盖原始服务.您可以执行以下操作:
If you doing "functional testing" then probably you should create test "dummy" service for "test" env which will overwrote original one. You can do something like that:
在 src/YourBundle/Resources/config/services.yml
services:
api.wp_bridge:
class: %api.wp_bridge.class%
arguments: [@service_container]
在 app/config/config.yml
parameters:
api.wp_bridge.class: "ApiBundle\Util\WordPressBridge"
在 app/config/config_test.yml
parameters:
api.wp_bridge.class: "ApiBundle\Util\TestWordPressBridge"
然后功能测试将使用"ApiBundle \ Util \ TestWordPressBridge"-因为它是在测试" env中执行的.
Then functional test will use "ApiBundle\Util\TestWordPressBridge" - cause it is executed in "test" env.
您可以尝试模拟容器并将其传递给测试内核,但是如果没有其他模拟库(在纯PHPUnit中),这可能会很痛苦.
You can try to mock container and pass it to test kernel but this can be painfull without some other mocking lib (in pure PHPUnit).
我个人使用 phpspec2 进行单元"测试,其中模拟很容易:)和一些接受条件" 我正在使用 behat 和
Personally I am using phpspec2 for "unit" testing where mocking is just easy :) and for some "acceptance criteria" stuff I am using behat and mink
这篇关于Symfony/PHPUnit模拟服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!