In this tutorial, you will learn to implement integration test of the JPA and Hibernate data layer in Spring Boot by using @DataJPATest annotation with in-memory database

@DataJPATest provides the following features

  • Configure in-memory test database
  • Auto scan @Entity classes
  • Auto configure Spring Data JPA, Hibernate and Data Source
  • Turn on SQL logging

Project dependencies

Include spring-boot-starter-test and hsqldb into your pom.xml file

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

<dependency>  
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>test</scope>
</dependency>  

spring-boot-starter-test contains some testing support libraries such as JUnit, Spring Test + Spring Boot Test, Mockito, AssertJ, Hamcrest and JsonPath

Define the test class

Run the tests with @RunWith(SpringRunner.class) and @DataJPATest

  • Use @RunWith(SpringRunner.class) class annotation to tell JUnit to run the unit tests in Spring's testing supports
  • Use @DataJPATest class annoation to test JPA and Hibernate layer

Inject dependencies with @Autowired

  • Inject TestEntityManager field
@Autowired
private TestEntityManager testEntityManager;  

TestEntityManager is designed for tests, provides an alternative to the JPA standard EntityManager

  • Inject the JPA Repository you want to test, for example
@Autowired
private ProductRespository productRespository;  

Verify the test result with AssertJ's assertThat(..).

  • Prefer AssertJ's assertThat to verify the test result for more readability, for example
// when
List<Product> products = productRespository.findAll();

// then
assertThat(products).hasSize(1);  

Implementation example


@DataJPATest by default will begin a new transaction before and roll back it after running a test method. You should see something like this in the console when running the test

Began transaction (1) for test context [[email protected] testClass = ProductRepositoryTest... testMethod = [email protected]  
...
Rolled back transaction for test:  [[email protected] testClass = ProductRepositoryTest... testMethod = [email protected]  

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-restapi-testing-all-layers