- Learn how to test JPA repositories with
@DataJpaTest - Understand the differences between in-memory databases and real databases for testing
- Get started with Testcontainers for PostgreSQL
- Understand transaction management, flushing, and cleanup in tests
- Practice using
@ServiceConnectionfor Testcontainers integration
@DataJpaTestfocuses on JPA repositories and configures an in-memory database by default- Use
@Testcontainersand@Containerfor PostgreSQL-based tests - Spring Boot's
@ServiceConnectionsimplifies Testcontainers configuration - Flyway migrations run automatically with
spring.jpa.hibernate.ddl-auto=validate - Be mindful of transaction boundaries in your tests
This exercise focuses on testing the BookRepository with JPA-specific test configuration.
Tasks:
- Open
Exercise1DataJpaTest.javain theexercisespackage - Implement tests for the repository methods
- Test both standard CRUD operations and custom queries
- Consider using Testcontainers for PostgreSQL-specific features
Tips:
@DataJpaTestautomatically configures an in-memory database- For PostgreSQL-specific tests, use Testcontainers with
@ServiceConnection - Test both positive and negative scenarios
- Be aware of the
searchBooksByTitleWithRankingnative query that requires PostgreSQL - The solution is available in
Solution1DataJpaTest.java