我正在开发一个Laravel应用程序。我现在正在中间件上进行单元测试。我对模仿路线有意见。
这是我的中间件类
class CheckIfDepartmentIdPresent
{
public function handle($request, Closure $next)
{
if (! $request->route()->hasParameter('department')) {
return abort(Response::HTTP_FORBIDDEN);
}
//check if the id is valid against the database,
//if it is valid then return $next($request)
return abort(Response::HTTP_FORBIDDEN);
}
}
我把中间件命名为department。目前
在单元测试中,我像这样编写我的第一个测试。
public function test_request_fail_if_id_parameter_is_missing_in_route()
{
Route::middleware('department.present')
->any('/department/test', function () {
return 'OK';
});
$response = $this->get('/department/test');
$this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode());
}
上述测试方法效果良好。它正在按预期工作。现在我想模仿这条路线。在中间件中,我得到如下路由参数。
$request->route('department');
所以我需要用参数模拟一条路线。如果我这样嘲笑。
$path = "/department/{$department->id}";
Route::middleware('department.present')
->any($path, function () {
return 'OK';
});
我的中间件仍然无法使用$request获取部门id->路线(“部门”)。因此,我需要用占位符来模拟一条路由,然后中间件将能够按名称获取路由参数值。我怎么能假装/嘲笑呢?有办法吗?