DEV Community

Cover image for A Guide to Testing Middleware in Laravel
Serhii
Serhii

Posted on

A Guide to Testing Middleware in Laravel

Greetings, fellow developers! 🌟

Today, we're diving into the exciting world of Laravel middleware testing. Middleware plays a vital role in filtering and securing HTTP requests before they reach your application's routes. Ensuring that your middleware works flawlessly is crucial for building robust and secure web applications. In this article, we'll explore how to create a simple middleware in Laravel and write tests to cover both successful and failed authorization scenarios.

Are you ready to bolster your testing skills and secure your routes with confidence? Let's get started on this middleware testing adventure! πŸš€

Creating the Middleware:

Our first step is to create a simple middleware that will handle authorization for a secret area of our application. We'll call it RequiredHeaderMiddleware, responsible for checking a specific header in incoming requests.

  • Open your terminal and run the following command to create the middleware:
php artisan make:middleware RequiredHeaderMiddleware
Enter fullscreen mode Exit fullscreen mode
  • Now, navigate to the app/Http/Middleware directory and open it and replace the content with the following code:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequiredHeaderMiddleware
{
    public const SECRET_ACCESS_HEADER = 'Secret-Access-Header';

    public function handle(Request $request, Closure $next): Response
    {
        $requestedHeader = $request->header(self::SECRET_ACCESS_HEADER);
        if (empty($requestedHeader)) {
            return response('This area needs authorization header', Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this middleware, we check for the presence of a Secret-Access-Header in the incoming request. If the header is missing, we return an unauthorized response, securing our secret area effectively.

Creating a Test Case:

Now, let's write some test cases to ensure our middleware behaves as expected in different scenarios.

  • Create a new test:
php artisan make:test RequiredHeaderMiddlewareTest
Enter fullscreen mode Exit fullscreen mode
  • Copy the following test code into the newly created file:
<?php

namespace Tests\Feature;

use App\Http\Middleware\RequiredHeaderMiddleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class RequiredHeaderMiddlewareTest extends TestCase
{
    public function testEndpointWithoutHeader(): void
    {
        // Given
        $request = Request::create(route('secret-place'));

        $next = function () {
            return response('This is a secret place');
        };

        // When
        $middleware = new RequiredHeaderMiddleware();
        $response = $middleware->handle($request, $next);

        // Then
        $this->assertEquals(Response::HTTP_UNAUTHORIZED, $response->getStatusCode());
        $this->assertEquals('This area needs authorization header', $response->getContent());
    }

    public function testWithCorrectHeader(): void
    {
        // Given
        $request = Request::create(route('secret-place'));
        $request->headers->set(RequiredHeaderMiddleware::SECRET_ACCESS_HEADER, 'foo-bar');

        $next = function () {
            return response('This is a secret place');
        };

        // When
        $middleware = new RequiredHeaderMiddleware();
        $response = $middleware->handle($request, $next);

        // Then
        $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
        $this->assertEquals('This is a secret place', $response->getContent());
    }
}
Enter fullscreen mode Exit fullscreen mode

In the test cases, we simulate two scenarios: one without the required header (which should return an unauthorized response), and one with the correct header (which should return the content of our secret place).

Conclusion:

Congratulations! πŸŽ‰ You've successfully created a custom middleware in Laravel and written test cases to ensure its proper functioning. Middleware testing is essential for securing your routes and guaranteeing smooth operations within your application.

P.S. If you found this article helpful, stay tuned for more exciting Laravel and testing content. I'll be sharing more tips and tricks to level up your development skills. Don't forget to follow me here on dev.to for updates! πŸš€

Top comments (0)