Testing with @DataJpaTest and Testcontainers
Fast recall
Quick revision
Core answer
Whether you can set up real-database integration tests and understand why H2 is an inadequate substitute
Forgetting @AutoConfigureTestDatabase(replace = NONE) — without it Spring replaces your DataSource with H2 even when Testcontainers is configured
Mention @Testcontainers and @Container for JUnit 5 lifecycle management, and using a shared static container to avoid restarting Postgres for every test class
Interview-ready guide
Interview answer
@DataJpaTest with the default H2 is fast but dangerous — H2's SQL dialect differs from production databases in subtle ways. A query that passes in H2 can fail in PostgreSQL due to different NULL handling, type casting, or function support.
Testcontainers runs the real database in Docker. Add @AutoConfigureTestDatabase(replace = NONE) to prevent Spring from replacing your DataSource with H2, then use @DynamicPropertySource to inject the container's JDBC URL.
The key pattern: make the container static so it starts once per test class, not once per test method. For large test suites, share a single container across all @DataJpaTest classes using a base class — the ~3 second container startup pays once instead of per class.
@DataJpaTest enables @Transactional by default, so each test method gets its own transaction that rolls back — tests don't pollute each other's data.
Testing with @DataJpaTest and Testcontainers
Direct Answer
Use @DataJpaTest with @AutoConfigureTestDatabase(replace = NONE) to prevent Spring from replacing your DataSource with H2. Declare a PostgreSQLContainer as a static @Container field and use @DynamicPropertySource to inject the container's JDBC URL, username, and password into the Spring context before it starts. This gives you tests that run against real Postgres with the same dialect, indexes, and constraints as production.
Common Mistakes & Pitfalls
Forgetting @AutoConfigureTestDatabase(replace = NONE) — without it Spring replaces your DataSource with H2 even when Testcontainers is configured
Check your understanding
Answer these without looking back at the article.
- How do you reset database state between tests in Testcontainers?
- What is @Sql and when would you use it?
- How do you test database transactions that should roll back?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.