Repository tests with @DataJpaTest
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
test custom queries against a real database quickly.
Planned topics
@DataJpaTestloads only JPA parts (entities, repositories), not the whole app.- By default it replaces the datasource with an embedded database; add
@AutoConfigureTestDatabase(replace = NONE)to keep your Testcontainers database. - Each test runs in a transaction that rolls back at the end.
- Test every custom query: derived queries with tricky conditions,
@Query, paging. - Flush and clear the persistence context if you want to see what the database really returns.
Draft outline details
Demonstration
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class ProductRepositoryTest {
@Container @ServiceConnection static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");
@Autowired ProductRepository repo;
}Check your understanding
Why add replace = NONE?
Show answer
To stop Spring swapping in an embedded database.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.