Mock Middleware for route testing in Laravel

Viewed 4704

I am trying to write some unit tests to ensure my routes are not accidentally rewritten. I found already an answer to check whether a correct controller is assigned to particular route here.

However I would like to check as well that correct middlewares are assigned to route. I tried similar approach with

$tmp = new CorsService;
$corsMiddleware = Mockery::mock('Barryvdh\Cors\HandleCors[handle]', array($tmp))
    ->shouldReceive('handle')->once()
    ->andReturnUsing(function($request, Closure $next) {
        return $next($request);
    });

\App::instance('Barryvdh\Cors\HandleCors', $corsMiddleware);

For some reason the test is not picking this up. I am assuming that is because middleware instances are not stored using App::instance.

What am I doing wrong?

3 Answers

Don't forget to to use ->getMock() at the end, if you are going to chain things like ->shouldReceive directly to your Mock object:

$corsMiddleware = Mockery::mock('Barryvdh\Cors\HandleCors[handle]', array($tmp))
    ->shouldReceive('handle')->once()
    ->andReturnUsing(function($request, Closure $next) {
        return $next($request);
    })
    ->getMock();
Related