Put tests next to what they’re testing in Laravel

This is a matter of personal preference, it basically means that if you have a file, say app/Services/Calculator.php and you wanted to write a test for this class, instead of hiding the test away in a tests/Unit/Services/CalculatorTest.php file, you would put the test right next to what it is testing, in app/Services/SubscriptionCalculatorTest.php

This approach has a few benefits:

  • Switching between implementation and tests is easier
  • Easily see which classes have tests without relying on code coverage tools
  • Remembering to update tests when refactoring

The approach has been championed by a few popular frameworks in the JS world — Angular, RedwoodJS, FoalTS, NestJS but for some reason, hasn’t really made its way into PHP.

Luckily, enabling this behaviour in Laravel is quite easy.

Move your unit tests next to your class

Remember to update the namespace!

Update phpunit.xml to find unit tests within your app directory

Image for post
Image for post

That’s it!

I’d also recommend checking out PestPHP for some Jest style testing in PHP land. The above setup *just works* and you don’t have to remember to update namespaces.

Note: I would recommend keeping Feature tests within the tests directory as they will be testing a whole range of different classes within your application.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store