Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HeyJanny's avatar

Testing repository in laravel

So I'm trying to write unit tests. At first i had service class that used models and their methods directly. I had a lot of trouble testing it due to static calls of methods like User::create(), basically it became one big mocking mess. Then i moved that logic to repositories like described here https://tallstackdev.medium.com/introduction-to-the-repository-pattern-in-laravel-c025eb1cc7fd. Tesing service became a breeze but guess what - i have to test repository too. Considering the two main principles:

  • unit tests should not rely on any database
  • it is bad to mock models in laravel how am I supposed to test the repository classes?
0 likes
2 replies
puklipo's avatar

Laravel tests can rely on a database. Throw away any assumptions. It is common to use in-memory SQLite.

It is prepared from the start to use in-memory SQLite. Remove the comments in phpunit.xml.

        <!-- <env name="DB_CONNECTION" value="sqlite"/> -->
        <!-- <env name="DB_DATABASE" value=":memory:"/> -->

https://github.com/laravel/laravel/blob/11.x/phpunit.xml

1 like
Tray2's avatar

The repository pattern is seldom a good idea, in my opinion. However, when it comes to unit and feature tests, I generally go with the principle, "Don't mock what you don't own", so in other words, don't mock the user creation, keep that in your feature tests instead, and hit the database, it is fast enough.

1 like

Please or to participate in this conversation.