Put tests next to what they’re testing in Laravel

Craig Morris
1 min readDec 1, 2020

--

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

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.

--

--