Why this matters
- H2 in MySQL compatibility mode still diverges from PostgreSQL on JSON columns, locking, and sequence behaviour — bugs slip through slice tests and appear only in staging.
- Testcontainers starts disposable containers per test class or suite, giving you a faithful environment without maintaining shared test infrastructure.
- Combined with
@SpringBootTest, you verify the full request path: HTTP → service → repository → real database → response.
Testcontainers
L1 · FresherSpin up real Postgres or Redis in Docker during tests — catches SQL dialect issues H2 misses.
@SpringBootTest
L2 · IntermediateLoads full application context with dynamic properties pointing JDBC URL to the container.
Parallel CI
L3 · AdvancedReuse containers with singleton patterns or Ryuk cleanup to keep pipeline times acceptable.
Contract with prod
L4 · ExpertMatch major versions (Postgres 15 in test and prod) to avoid JSON operator and index differences.
JUnit test
Kafka container
Assert events
Integration test building blocks
@SpringBootTest(webEnvironment = RANDOM_PORT)— boots the full application on a random port.@Testcontainers— JUnit 5 extension that manages container lifecycle.@Container+static— shared container across all tests in the class (faster startup).@DynamicPropertySource— injects container host/port into Spring's environment before context loads.TestRestTemplate/RestClient— send real HTTP requests to the running application.
Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 3 sections
- PostgreSQL integration test
- Redis cache integration test
- Kafka end-to-end test
Test yourself
Answer these before moving on — recall is what makes it stick.