Mocking a call with chained methods and arguments

后端 未结 2 1365
无人及你
无人及你 2021-01-05 20:35

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

相关标签:
2条回答
  • 2021-01-05 21:03

    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

    0 讨论(0)
  • 2021-01-05 21:18

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

    0 讨论(0)
提交回复
热议问题