How to test a middleware with phpunit in laravel?

Member

by lew , in category: PHP Frameworks , 6 months ago

How to test a middleware with phpunit in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 6 months ago

@lew 

To test a middleware in Laravel with PHPUnit, you can follow these steps:

  1. Create a new test class for your middleware in the tests/Feature or tests/Unit directory of your Laravel project. You can create a new test class with the PHP artisan command:
1
php artisan make:test MyMiddlewareTest


  1. In the test class, use the RefreshDatabase trait to ensure that the database is in a clean state before running the test. You can add the trait like this:
1
2
3
4
5
6
7
8
9
use IlluminateFoundationTestingRefreshDatabase;
use TestsTestCase;

class MyMiddlewareTest extends TestCase
{
    use RefreshDatabase;

    // Your test methods will go here
}


  1. Write your test method to test the behavior of your middleware. You can use the actingAs method to authenticate a user and the get or post methods to send a request through the middleware. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public function test_middleware()
{
    // Authenticate a user
    $user = factory(User::class)->create();
    $this->actingAs($user);

    // Send a request through the middleware
    $response = $this->get('/protected-route');

    // Assert that the response is successful
    $response->assertStatus(200);
}


  1. Run your test using PHPUnit. You can run all tests in your project by running:
1
vendor/bin/phpunit


Your middleware test will execute and you will see the results in the terminal. Make sure to test both the positive and negative scenarios to ensure that your middleware is working as expected.