How to mock chain of methods with PHPUnit test

mocking, php, phpunit, unit-testing

Solution

it's simpler now with Mocking Demeter Chains And Fluent Interfaces

simply

$dbMock = $dbMock
        ->expects(self::any())
        ->method('getFinder->find')
        ->with('questions')
        ->will($this->returnValue('7'));

another example from mockery docs

$object->foo()->bar()->zebra()->alpha()->selfDestruct();

and you want to make `selfDestruct` to return `10`

$mock = \Mockery::mock('CaptainsConsole');
$mock->shouldReceive('foo->bar->zebra->alpha->selfDestruct')->andReturn(10);

Problem

I'm trying to mock a chain (nested) of methods to return the desired value , this is the code : ``` public function __construct($db) { $this->db = $db; } public function getResults() { return $this->db->getFinder()->find($this->DBTable); } ``` I tried this mock but it does not work : ``` $dbMock = $this->createMock(DB::class); $dbMock = $dbMock ->expects(self::any()) ->method('getFinder') ->method('find') ->with('questions') ->will($this->returnValue('7')); ``` Any solutions how to solve such a problem ? Thank you .

Original source

Related problems