Spring Data JPA Test

Spring%20Boot%20Data%20JPA%20Test%20Docs 2088E9?logo=quickLook&logoColor

DataJpaTest

@DataJpaTest

A Spring Boot test splice which creates a JPA environment for the Repository under a test. Dependencies of it are not included and need to be added to the Spring Context in the test environment.

By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource).
@Import

Indicates one or more component classes to import - typically @Configuration classes.

Testing Repository methods

@Autowired
BookRepository bookRepository;

@Test
void testSaveBook() {
    Book savedBook = bookRepository.save(Book.builder()
            .name("My Book")
            .price(new BigDecimal("11.99"))
            .build());

    bookRepository.flush(); (1)

    assertThat(savedBook).isNotNull();
    assertThat(savedBook.getId()).isNotNull(); (2)
}
1 ⚪ JpaRepository<T,ID>#flush() flushes all pending changes to the database.
2 Id will be generated by Hibernate.