🎯 What you will learn
Integration tests verify that multiple components work together correctly — repository + real database, Spring context + JPA, SQL migrations + entity mapping. Testcontainers automates Docker container lifecycle so you get real PostgreSQL in CI without manual setup. By the end of this lesson you will understand:
- The difference between unit tests, integration tests, and end-to-end tests
@Testcontainers+@Containerto start/stop Docker containers from JUnit 5PostgreSQLContainerwith dynamic URL injection into Spring@AutoConfigureTestDatabase(replace=NONE)— why it's required@DataJpaTestwith H2 as a Docker-free alternative@Sqlfor per-test fixture data insertion- How to share one container across multiple test classes
💼 Real-world scenario
Unit tests with mocked repositories never caught the N+1 query that slowed production. Rohan adds Testcontainers: JUnit 5 starts a disposable PostgreSQL Docker container before the test class, Spring Boot connects to it, and every @DataJpaTest runs against real SQL. The container is destroyed when tests finish.
🐋 pom.xml dependencies + Testcontainers setup
Add the Testcontainers BOM and the postgresql + junit-jupiter modules. The spring-boot-starter-test already pulls in JUnit 5 and AssertJ. Requires Docker Desktop or Docker Engine running locally or in CI.
Spring Boot 3.1+ shortcut: Spring Boot 3.1 introduced @ServiceConnection which auto-discovers the Testcontainers PostgreSQL container and configures the datasource URL automatically — no manual @DynamicPropertySource needed.
🧪 @Testcontainers + @Container integration test
Declare the container as a static field annotated with @Container — one container instance for the whole class. @AutoConfigureTestDatabase(replace=NONE) prevents Spring from silently swapping your datasource for H2.
static @Container is critical: A non-static @Container starts a new Docker container for every test method — extremely slow (4+ seconds per container start). Declaring it static reuses one container for the entire class.
⚡ @DataJpaTest with H2 — Docker-free alternative
@DataJpaTest is a Spring slice test: it loads only the JPA layer (no web, no security, no service beans) and by default uses an in-memory H2 database. Ideal for CI environments without Docker, or for fast feedback on repository logic that doesn't rely on PostgreSQL-specific features.
📋 Testcontainers vs @DataJpaTest
| Aspect | Testcontainers + @SpringBootTest | @DataJpaTest + H2 |
|---|---|---|
| Database | Real PostgreSQL (Docker) | H2 in-memory (JVM) |
| Speed | Slow (~4–10s for container start) | Fast (~1–2s) |
| Fidelity | Identical to production | SQL dialect differences possible |
| Docker required | Yes | No |
| Spring context | Full (@SpringBootTest) | JPA layer only |
| PostgreSQL-specific SQL | Supported (JSONB, window fns) | Not supported |
| Best for | True integration tests, CI with Docker | Fast unit-level repo tests, simple CI |
🎤 Interview Q&A
Unit test: tests one class in isolation; all dependencies mocked. Fast (milliseconds). Integration test: tests multiple components together (e.g., repository + real database). Slower (seconds) but catches wiring bugs that mocks miss.
Yes. @DataJpaTest wraps each test in a transaction and rolls it back after the test completes. Test data doesn't persist between tests. Override with @Transactional(propagation = NOT_SUPPORTED) to commit.
A @DynamicPropertySource static method on the test class (or a Testcontainers initialiser) calls DynamicPropertyRegistry.add("spring.datasource.url", container::getJdbcUrl) before the Spring context starts. Spring reads this property when configuring the datasource.
@SpringBootTest loads the entire application context (slow, ~3-5s). Slice annotations (@DataJpaTest, @WebMvcTest, @JsonTest) load only the layer they target — much faster. Use slices for focused component tests; full @SpringBootTest for end-to-end integration.
Use a @Container static field in a shared abstract base class, or use Testcontainers' static container lifecycle. A common pattern: declare the container as a static field with @ClassRule (JUnit 4) or in a companion object (@Container + @Testcontainers at class level on a base class). For JUnit 5 + Spring Boot, use the Testcontainers service loader (ServiceLoader<TestcontainersConfiguration>) which is auto-configured since Spring Boot 3.1.
📝 Quiz — 5 questions
Next: Calling an LLM from Java →
⚠️ Common mistakes
replace=NONE when using Testcontainers.@Container starts a new Docker container for each test method — extremely slow. Declare it static to reuse one container for the whole class.@DataJpaTest + H2 as a fast fallback, or configure GitHub Actions / GitLab CI with Docker-in-Docker. Some CIs have Docker available by default.@Sql specific test data or use a seed migration for integration tests.✅ Key takeaways
- Testcontainers starts a real PostgreSQL Docker container for each test run — same DB as production
- @DataJpaTest + H2 is the Docker-free alternative: loads only the JPA layer, fast and portable
- static @Container reuses one Docker container per class — don't start per method
- @AutoConfigureTestDatabase(replace=NONE) is required to use Testcontainers instead of H2
- Layer tests appropriately: unit (mocks) → @DataJpaTest (JPA) → @SpringBootTest (full stack)
From integration tests to AI-powered Java services
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →