模拟中间件在Laravel中进行路由测试

时间:2016-03-07 15:58:56

标签: unit-testing laravel mocking phpunit middleware

我正在尝试编写一些单元测试,以确保我的路由不会被意外重写。我找到了一个答案,检查是否将正确的控制器分配给特定路由here

但是,我还要检查是否已将正确的中间件分配给路由。我用

尝试了类似的方法
function World(plan){
  this.plan = plan;  
}

World.prototype.toString = function() {
    return this.plan.join('\n');
};

var world = new World(["––––––––––",
                      "|   _    |",
                      "|  |     |",
                      "|__|     |",
                      "| ___|   |",
                      "––––––––––"]);
                     
console.log(world.toString());

由于某些原因,测试没有提到这一点。我假设这是因为中间件实例未使用$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); 存储。

我做错了什么?

3 个答案:

答案 0 :(得分:4)

所以我发现上面代码有两个问题

  1. 您无法直接使用->shouldReceive
  2. 的返回值链接Mockery::mock
  3. Closure缺少\
  4. 工作示例:

    $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);
    

答案 1 :(得分:0)

尝试获取路由并检查其中间件

// Get Routes
    foreach (Route::getRoutes() as $route) {
        $middleware = $route->gatherMiddleware();
        $name = $route->getName();
        \Log::debug($name.'--');
        \Log::debug($middleware);
    }

答案 2 :(得分:0)

如果要直接将->getMock()之类的东西链接到您的Mock对象,请不要忘记最后使用->shouldReceive

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