Mocking a call with chained methods and arguments
Asked Answered
D

1

5

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.

Departure answered 19/5, 2014 at 22:9 Comment(0)
C
9

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

Cassy answered 22/5, 2014 at 12:53 Comment(1)
I recently learned about the method that does not care about arguments. Wasn't aware of the second method ThanksDeparture

© 2022 - 2024 — McMap. All rights reserved.