Laravel: Middleware Unit Test

By | April 14, 2020

Assalamualaikum / Hi,

If you are working on a package, have a middleware and you want to write a unit test for it.

Assuming you have the following middleware:

So how you going to test it? The following gist, explained the setup.

With this approach, we test just the middleware it self. Not related to any other process. Hence, your unit test is significantly small.

What kind of assertions? Depends on what your middleware are doing. In our case right now, is the learn value are available after go through the middleware.

UPDATE: 2020-04-14 08:32

You may want to use the following approach, avoid make any changes when there’s changes on the other part of framework workflow:

The result still the same.

Laravel Unit tests extends from class `PHPUnit\Framework\TestCase` instead of `Tests\TestCase`. This is due to the understanding that Unit test doesn’t boot the the framework, while Feature always boot the framework. Information shared in Laravel Malaysia Telegram Group, by @crynobone aka Mior Muhammad Zaki aka Miki.

That’s all folks!

Thank you,
Nasrul Hazim.

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − eleven =