I am developing a Laravel application. I am now doing Unit testing on the Middleware. I am having a problem with mocking the route.
This is my middleware class
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);
}
}
I named the middleware as department.present.
In the unit test I write my first test like this.
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());
}
The above test method is working fine. It is working as expected. Now I want to mock the route. In the middleware, I am getting the route parameter like this.
$request->route('department');
So that I need to mock a route with parameter. If I mocked like this.
$path = "/department/{$department->id}";
Route::middleware('department.present')
->any($path, function () {
return 'OK';
});
My middleware still not be able to fetch the department id using $request->route('department'). So I need to mock a route with a placeholder for the parameter and then the middleware will be able to fetch the route parameter value by name. How can I fake/mock that? Is there a way to do that?