Skip to content
Ameen Abozaid
Planned lessonJNR-045-L03

Repository tests with @DataJpaTest

  • Lesson 3 of 7
  • Junior
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

  • @DataJpaTest loads 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

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.