3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • In the first case when you `dd($request->route('department'))` you should be getting `test`, is that happening? – Mozammil Jan 22 '19 at 13:03
  • 1
    Nope because I have not defined the placeholder for the variable. That is what I am finding out. – Wai Yan Hein Jan 22 '19 at 13:28
  • 1
    Just stumbled across the same problem, unit testing rules in a request that use a route parameter as context. – Elliot Jun 29 '20 at 07:52

0 Answers0