Search code examples
unit-testinglaravelmockingphpunitmiddleware

Mock Middleware for route testing in Laravel


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?


Solution

  • So I have found out there are 2 issues with above code

    1. You can not chain ->shouldReceive directly with return value of Mockery::mock
    2. there is missing \ from Closure

    Working example:

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