Search code examples
springspring-bootintegration-testingspring-repositories

Should repositories in Spring Boot applications be tested directly?


Not sure if this will be considered a "legitimate question" or "purely opinion based", but is there a "best practice" with regards to directly testing a repository in a Spring Boot application? Or, should any integration testing simply target the associated service?

The reasoning for the question is simply the fact that, for the most part, a repository in a Spring Boot application contains no project-generated code. At best, it contains project-defined method signatures which Spring generates implementations for (assuming correct naming conventions).

Thanks...


Solution

  • If you can mess it up, you should test it. Here the opportunities to mess up can include:

    • Custom Queries (using @Query) might be wrong (there can be all kinds of logic mistakes or typos writing a query with no compile-time checking)
    • Repository methods where the query is derived from the method name might not be what you intended.
    • Arguments passed in, the type on the parameter list might not match the type needed in the query (nothing enforces this at compile time).

    In all these cases you're not testing Spring Data JPA, you're testing the functionality you are implementing using Spring Data JPA.

    Cases of using provided methods out of the box, like findOne, findAll, save, etc., where your fingerprints are not on it, don't need testing.

    It's easy to test this stuff, and better to find the bugs earlier than later.