Mocking a call with chained methods and arguments

蹲街弑〆低调 提交于 2019-12-03 21:17:55

问题


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

Another use could be like:

$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.


回答1:


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')...

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




回答2:


If you are happy with a syntax like this

$db = m::stub('Database', array(
   'select(someTblName)->where(fieldName,someValue)->runQuery->fetch' => 'return stuff',
   'select(someOtherTblName)->where(...)->runQuery->fetch' => 'return other stuff'

));

you can use a small Mockery helper/extension I've just written

https://github.com/elvisciotti/mockery-stub-chain-args

alpha version, I'll probably improve it soon



来源:https://stackoverflow.com/questions/23748005/mocking-a-call-with-chained-methods-and-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!