PHPUnit Mock稍后更改期望 [英] PHPUnit Mock Change the expectations later

查看:81
本文介绍了PHPUnit Mock稍后更改期望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的用例.我想要一个setUp方法,该方法将使我的模拟对象返回默认值:

I have a simple use case. I want to have a setUp method which will cause my mock object to return a default value:

$this->myservice
        ->expects($this->any())
        ->method('checkUniqueness')
        ->will($this->returnValue(true));

但是随后在一些测试中,我想返回一个不同的值:

But then in some tests, I want to return a different value:

$this->myservice
        ->expects($this->exactly(1))
        ->method('checkUniqueness')
        ->will($this->returnValue(false));

我过去曾使用GoogleMock for C ++,它具有"returnByDefault"或用于处理该问题的工具.我不知道在PHPUnit中是否可以做到这一点(没有api文档,并且很难阅读代码来找到我想要的东西.)

I've used GoogleMock for C++ in the past and it had "returnByDefault" or something to handle that. I couldn't figure out if this is possible in PHPUnit (there is no api documentation and the code is difficult to read through to find what I want).

现在我不能只将$this->myservice更改为新的模拟,因为在安装程序中,我将其传递给其他需要模拟或测试的东西.

Now I can't just change $this->myservice to a new mock, because in setup, I pass it into other things that need to be mocked or tested.

我唯一的其他解决方案是我失去了设置的好处,而不得不为每个测试构建所有模拟.

My only other solution is that I lose the benefit of the setup and instead have to build up all of my mocks for every test.

推荐答案

您可以将setUp()代码移到另一个具有参数的方法中.然后从setUp()调用此方法,您也可以从测试方法中调用它,但是其参数与默认参数不同.

You could move the setUp() code into another method, which has parameters. This method gets then called from setUp(), and you may call it also from your test method, but with parameters different to the default ones.

这篇关于PHPUnit Mock稍后更改期望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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