Search This Blog

Spring Data JPA Repository Testing using Spring Boot @DataJpaTest

In this article, we will learn how to test Spring Data JPA Repositories using Spring Boot provided @DataJpaTest annotation.

Sometimes we might want to test the persistence layer components of our application, which doesn’t require the loading of many components like controllers, security configuration, and so on. Spring Boot provides the @DataJpaTest annotation to test the Spring beans, which talk to relational databases.

If you want to run the tests against the actual registered database, you can annotate the test with @AutoConfigureTestDatabase(replace=Replace.NONE), which will use the registered DataSource instead of an in-memory datasource.

8. Running Tests

When you run EmployeeRepositoryTests, Spring Boot will autoconfigure the H2 in-memory embedded database (as you have the H2 database driver in the classpath) and run the tests.
The output of the tests shown in below screenshot:

@DataJpaTest with TestEntityManager

The @DataJpaTest annotation also autoconfigures TestEntityManager, which is an alternative to the JPA EntityManager to be used in JPA tests.