Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 630
Marian Bazalik Avatar asked Feb 08 '23 13:02

Marian Bazalik


2 Answers

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);
like image 101
Marian Bazalik Avatar answered Feb 10 '23 10:02

Marian Bazalik


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();
like image 25
Michael Avatar answered Feb 10 '23 11:02

Michael