使用链接的方法和参数模拟呼叫 [英] Mocking a call with chained methods and arguments

查看:99
本文介绍了使用链接的方法和参数模拟呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用模拟来运行某些单元测试,而我不确定该如何模拟我的数据库类.它由可以像以下两个示例一样链接的单独方法组成:

Im learning how to use mockery in order to run some unit test and Im not sure what to do to mock my database class. It consists of separate methods that can be chained like these two examples:

$db->select('someTblName',['fieldName'])
   ->where('fieldName', 'someValue')
   ->runQuery()
   ->fetch(); //returns array or null

另一种用途可能是:

$db->select('someTblName')
   ->where('fieldName', 'someValue')
   ->where('fieldName', array('>=' , 'someValue')
   ->runQuery()
   ->fetch(); //returns array or null

通过阅读一些文档,我发现我可以做类似的事情:(对于第一种情况)

From reading some of the documentation I see that I can do something like:(for the first case)

$db = \Mockery::mock('Database');
$db->shouldReceive('select', 'where', 'runQuery', 'fetcth')
    ->with(??????)
    ->andReturn(null);

现在我对如何将对应"参数传递给方法感兴趣吗?而且,我将如何模拟第二种情况.

Now Im interested on how to pass the "corresponting" parameters to the methods? And, how would I mock the second scenario.

推荐答案

如果您不关心参数,则可以执行shouldReceive('select->where->runQuery->fetch').如果确实要检查参数,则必须执行以下操作来链接期望值:

You can do shouldReceive('select->where->runQuery->fetch') if you do not care about the arguments. If you do want to check the arguments, you have to do the following to chain expectations:

$db->shouldReceive('select')->with('someTblName', ['fieldName'])
    ->once()->andReturn(m::self())->getMock()
    ->shouldReceive('where')...

最后一个shouldReceive应该是shouldReceive('fetch')->andReturn(null).

The last shouldReceive would be shouldReceive('fetch')->andReturn(null).

这篇关于使用链接的方法和参数模拟呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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