SoCal
SoCal

Reputation: 841

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...

Upvotes: 3

Views: 1455

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96454

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.

Upvotes: 6

Adina Rolea
Adina Rolea

Reputation: 2109

Starting from the idea that repositories should be used only inside services and services are used to interact with the other layers of the system, I would say that testing services should be enough in the majority of cases.

I would not test standard repository methods like findAll, or findBy.., they were tested already and the purpose is not to test JPA, but rather the application.

The only repository methods that should have direct tests are the ones with custom queries. These queries may be located in a shared library and it is not efficient to write similar tests across different projects(in this case regression is a big concern)

Upvotes: 0

Leandro Rosa
Leandro Rosa

Reputation: 96

Yes, I think is a good pratice to do that. You could use @DataJpaTest annotation, it starts a in memory database. The official documentation says:

You can use the @DataJpaTest annotation to test JPA applications. By default, it configures an in-memory embedded database, scans for @Entity classes, and configures Spring Data JPA repositories. Regular @Component beans are not loaded into the ApplicationContext.

Link to the docs: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

Upvotes: 0

Related Questions