Search code examples
phpmockery

How to get Mockery to work with a demeter chain


I have a Slim application that has some Middleware.

It performs authentication for the route, and retrieves the route like so:

$route = $this->getApplication()->router()->getCurrentRoute();

I'm now testing it and am attempting to use Mockery to mock the result of the chained call, so I can effectively specify the route.

$mock = M::mock('\Api\SessionMiddleware[getApplication]');
$mock->shouldReceive('router->getCurrentRoute')->andReturn('myRoute');

This doesn't work. It tries to call: require('lib/demeter/router.php') and fails as this doesn't exist.

I've also tried:

$mock = M::mock('\Api\SessionMiddleware')->shouldDeferMissing();
$mock->shouldReceive('getApplication->router->getCurrentRoute')->andReturn('myRoute');

This doesn't work either, failing with:

Failed opening required 'lib/demeter/getApplication.php'

What am I missing?


Solution

  • You also need to mock the router. and let the router() method return the router mock in turn.

    $mock = M::mock('\Api\SessionMiddleware[getApplication]');
    $routerMock = M::mock('My\Router');
    $routerMock->shouldReceive('getCurrentRoute')->andReturn('myRoute');
    $mock->shouldReceive('router')->andReturn($routerMock);