An Approach to Testing Middleware

TJ Miller
No relation, I just liked this image — Joey Pilgrim —

I’ve always tested middleware in one of two ways, a unit test with mocks and asserting the callback in the handle method or integration tests on application routes.

Unit Testing

The problem with unit testing is that you don’t have any visibility into if the middleware is actually active and you also don’t know how it will function as the request is passed through other active middleware.

Integration Testing

Using integration tests on application routes resolves some of the issues with unit testing middleware but it makes it a little bit harder to make assertions on how the middleware is actually functioning. I also found myself wanting to constantly verify that the middleware was active and working on each of my application routes.

Testing the Middleware

I wanted to find a simple approach that verified the following:

  • Middleware is active, and configured correctly (global, group, single use)
  • Middleware is functioning correctly

Lets take a look at some examples

So what I’ve done here is define custom testing routes and applied the middleware as I would use it in the application routes, in this case global middleware and as middleware for the api group. This allows me to assert that the middleware is configured and functioning correctly.

The only potential drawback to this approach is that it still relies on the developer to ensure the application routes are assigned middleware correctly. This could still be mitigated by testing what middleware is active on each route. This isn’t something I typically worry about though.

TJ Miller

Written by

TJ Miller

Director of Application Development @ International Bancard | Laravel, Vue, Docker, Node

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade