Spring Data JPA - testing

TODO

https://reflectoring.io/spring-boot-data-jpa-test/

@DataJpaTest example for Spring Data Repository Unit Test: https://www.bezkoder.com/spring-boot-unit-test-jpa-repo-datajpatest/

Unit testing for jpa code

How to write unit tests for JpaRepository interfaces?

Use @DataJpaTest with TestEntityManager.

For testing, we’ll work with H2 in-memory database. It eliminates the need for configuring and starting an actual database.

@DataJpaTest annotation for testing JPA Repositories

@DataJpaTest is the annotation that Spring supports for a JPA test that focuses only on JPA components.

It will disable full auto-configuration and then, apply only enable configuration relevant to JPA tests. The list of the auto-configuration settings that are enabled can be found here: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-test-auto-configuration.html#test-auto-configuration

By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. If you don’t want it, you can disable transaction management for a test or for the whole class using @Transactional annotation:

@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class YourNonTransactionalTests {

}

In-memory embedded database (like H2 database in this example) generally works well for tests. They are fast and do not require any installation. However, we can configure for a real database with @AutoConfigureTestDatabase annotation:

@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
class YourRepositoryTests {

}

If you are using JUnit 4, you need to add @RunWith(SpringRunner.class) to the test:

@RunWith(SpringRunner.class)
@DataJpaTest
class YourRepositoryTests {

}