🎯 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 + @Container to start/stop Docker containers from JUnit 5
  • PostgreSQLContainer with dynamic URL injection into Spring
  • @AutoConfigureTestDatabase(replace=NONE) — why it's required
  • @DataJpaTest with H2 as a Docker-free alternative
  • @Sql for per-test fixture data insertion
  • How to share one container across multiple test classes
💼 Interview reality: "How do you write integration tests for a JPA repository?" is asked in virtually every senior Java/Spring backend interview. Knowing Testcontainers vs @DataJpaTest and their trade-offs demonstrates production maturity.

💼 Real-world scenario

💼
TaxSetu (Bangalore, India)
Real database — no mocks, no surprises

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.

# Requires Docker Desktop or Docker Engine running
pom.xmlLesson 33 · Testcontainers dependencies
output — with Docker running
[INFO] Running io.taxsetu.AccountRepositoryIT 🐋 Pulling image: postgres:16-alpine 🐋 Container postgres:16-alpine started in PT4.382S ✔ PostgreSQL 16 ready to accept connections [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS

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.

# Dynamic URL injected by Testcontainers
AccountRepositoryIT.javaLesson 33 · @Testcontainers + @Container
output — representative with Docker running
🐋 Container postgres:16-alpine started ...testing against real PostgreSQL 16... [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

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.

mvn test -Dtest=AccountRepositoryTest
AccountRepositoryTest.javaLesson 33 · @DataJpaTest + H2 + @Sql
verified output — H2, no Docker needed
[INFO] Running io.southbank.AccountRepositoryTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.2 s [INFO] BUILD SUCCESS

📋 Testcontainers vs @DataJpaTest

AspectTestcontainers + @SpringBootTest@DataJpaTest + H2
DatabaseReal PostgreSQL (Docker)H2 in-memory (JVM)
SpeedSlow (~4–10s for container start)Fast (~1–2s)
FidelityIdentical to productionSQL dialect differences possible
Docker requiredYesNo
Spring contextFull (@SpringBootTest)JPA layer only
PostgreSQL-specific SQLSupported (JSONB, window fns)Not supported
Best forTrue integration tests, CI with DockerFast unit-level repo tests, simple CI

🎤 Interview Q&A

EasyWhat is the difference between a unit test and an integration test?
+

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.

EasyDoes @DataJpaTest roll back transactions automatically?
+

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.

MediumHow does Testcontainers inject the dynamic database URL into Spring?
+

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.

MediumWhat is a @SpringBootTest slice annotation vs full @SpringBootTest?
+

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

HardHow do you share a single Testcontainer across multiple test classes without restarting it?
+

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

Question 1 of 5
What does @Testcontainers do on a JUnit 5 class?
Question 2 of 5
Why use Testcontainers over an in-memory H2 database?
Question 3 of 5
What does @DataJpaTest load?
Question 4 of 5
What does @AutoConfigureTestDatabase(replace=NONE) do?
Question 5 of 5
What does @Sql("/test-data.sql") do?
0
/ 5
Quiz complete!

Next: Calling an LLM from Java →

⚠️ Common mistakes

Forgetting @AutoConfigureTestDatabase(replace=NONE)
Spring Boot will silently replace your Testcontainers datasource with H2, and your test never touches PostgreSQL. Always add replace=NONE when using Testcontainers.
Not making the @Container field static
A non-static @Container starts a new Docker container for each test method — extremely slow. Declare it static to reuse one container for the whole class.
Running Testcontainers in CI without Docker
Testcontainers needs Docker. Use @DataJpaTest + H2 as a fast fallback, or configure GitHub Actions / GitLab CI with Docker-in-Docker. Some CIs have Docker available by default.
No @Sql or seed data — testing against empty tables
A test that finds no results because the table is empty will pass vacuously. Always @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)
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →