Java Testcontainers Integration Tests
How to use Testcontainers in JUnit5 to spin up real Postgres, Redis, and Kafka containers for integration tests that are reliable and reproducible.
Overview
Testcontainers spins up real Docker containers (Postgres, Redis, Kafka, etc.) during your test lifecycle. Rather than simulating your database, your tests hit a real engine: same SQL dialect, same connection pooling, same edge cases. The container comes up before the tests and goes away after them, so nothing leaks between runs.
You pay 5–15 seconds of container startup and get fidelity back. A real Postgres surfaces problems that mocks and H2 wave through quietly — actual SERIAL columns, JSONB operators, advisory locks, isolation-level behavior. For a deeper strategy on when that trade-off pays off, see Testcontainers: Real Dependencies in Integration Tests.
When to Use
- Integration tests that need a real database (Postgres, MySQL, MongoDB)
- Testing code that relies on engine-specific SQL (JSONB, arrays, full-text search)
- Verifying migration scripts against a real schema
- Testing message consumers with a real Kafka or RabbitMQ broker
- Testing against a real Redis for cache invalidation logic
When NOT to Use
- Unit tests — mocks are faster and sufficient for logic-only tests
- CI environments without Docker — Testcontainers requires a Docker daemon
- Tests that must run in seconds — container startup adds 5-15 seconds per container
- Testing HTTP clients — use WireMock instead (lighter and faster); see WireMock stub recipes
Solution
Setup with Maven
Import the BOM once and reference modules without versions:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>1.21.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<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>
</dependencies>
Setup with Gradle
testImplementation platform('org.testcontainers:testcontainers-bom:1.21.3')
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
Postgres container with JUnit5
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
class PostgresIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
@Test
void shouldCreateAndQueryTable() throws Exception {
try (Connection conn = DriverManager.getConnection(
postgres.getJdbcUrl(),
postgres.getUsername(),
postgres.getPassword());
Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE users (id SERIAL PRIMARY KEY, email TEXT UNIQUE)");
stmt.execute("INSERT INTO users (email) VALUES ('alice@example.com')");
ResultSet rs = stmt.executeQuery("SELECT email FROM users");
rs.next();
assertThat(rs.getString("email")).isEqualTo("alice@example.com");
}
}
}
Redis container
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import redis.clients.jedis.Jedis;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
class RedisIntegrationTest {
@Container
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
.withExposedPorts(6379);
@Test
void shouldSetAndGetValue() {
String host = redis.getHost();
Integer port = redis.getMappedPort(6379);
try (Jedis jedis = new Jedis(host, port)) {
jedis.set("test-key", "test-value");
assertThat(jedis.get("test-key")).isEqualTo("test-value");
}
}
}
Kafka container
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.testcontainers.utility.DockerImageName;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
class KafkaIntegrationTest {
@Container
static KafkaContainer kafka = new KafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:7.6.1")
);
@Test
void shouldProduceAndConsume() {
Properties producerProps = new Properties();
producerProps.put("bootstrap.servers", kafka.getBootstrapServers());
producerProps.put("key.serializer", StringSerializer.class.getName());
producerProps.put("value.serializer", StringSerializer.class.getName());
try (Producer<String, String> producer = new KafkaProducer<>(producerProps)) {
producer.send(new ProducerRecord<>("test-topic", "key", "hello-kafka"));
}
Properties consumerProps = new Properties();
consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
try (Consumer<String, String> consumer = new KafkaConsumer<>(consumerProps)) {
consumer.subscribe(Collections.singletonList("test-topic"));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(10));
assertThat(records.iterator().hasNext()).isTrue();
assertThat(records.iterator().next().value()).isEqualTo("hello-kafka");
}
}
}
Shared container pattern for faster tests
public abstract class BaseIntegrationTest {
static final PostgreSQLContainer<?> SHARED_POSTGRES;
static {
SHARED_POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withReuse(true);
SHARED_POSTGRES.start();
}
protected String getJdbcUrl() {
return SHARED_POSTGRES.getJdbcUrl();
}
}
Using @DynamicPropertySource with Spring Boot
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@Testcontainers
@SpringBootTest
class UserRepositoryIntegrationTest extends BaseIntegrationTest {
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", SHARED_POSTGRES::getJdbcUrl);
registry.add("spring.datasource.username", SHARED_POSTGRES::getUsername);
registry.add("spring.datasource.password", SHARED_POSTGRES::getPassword);
}
@Autowired
private UserRepository userRepository;
@Test
void shouldSaveAndFindUser() {
User user = new User("alice@example.com", "Alice");
userRepository.save(user);
User found = userRepository.findByEmail("alice@example.com");
assertThat(found).isNotNull();
assertThat(found.getName()).isEqualTo("Alice");
}
}
On Spring Boot 3.1+ you can drop @DynamicPropertySource entirely: annotate the container field with @ServiceConnection and Spring auto-configures the datasource from it.
How It Works
When JUnit picks up a class annotated with @Testcontainers, the extension walks the fields, finds the @Container ones, and boots them. Static fields boot once per class; instance fields boot before every test method. Each container then goes through this lifecycle:
Once the container is up, readiness and cleanup are automatic too:
Three details matter more than the API surface:
- Mapped ports are random. Never hardcode
localhost:5432— ask the container withgetHost()andgetMappedPort(5432). This is what lets builds run in parallel without port clashes. - A wait strategy gates the first test. Testcontainers blocks until the container reports readiness (a port listening, a log line, an HTTP check).
Wait.forLogMessage(".*database system is ready.*")is the escape hatch when the default wait is too optimistic. - Ryuk is the reaper. A tiny sidecar container watches your test JVM; if it dies mid-test, Ryuk still destroys everything it started. That sidecar is what keeps a crashed build from leaving containers running on your machine.
Static, instance, or reused containers?
| Pattern | Lifecycle | Startup cost | When to pick it |
|---|---|---|---|
@Container static | Once per test class | One startup per class | Default for almost everything |
@Container (instance) | Once per test method | Full startup per test | When each test needs a pristine container |
withReuse(true) | Survives across runs | ~0 after the first run | Local development only |
Reuse mode needs testcontainers.reuse.enable=true in ~/.testcontainers.properties, and it’s a developer-machine feature: containers are kept after the JVM exits, so a CI runner would accumulate them. For CI, prefer a shared static container plus @Transactional rollback or a @BeforeEach cleanup.
What about H2 or mocks instead?
| Approach | Fidelity | Speed | Catches real DB issues |
|---|---|---|---|
| Mockito mocks | None (you fake the answers) | Fastest | Never |
| H2 / embedded | Medium (different dialect) | Fast | Sometimes — MODE=PostgreSQL helps but isn’t Postgres |
| Testcontainers | Real service | 5-15s startup | Yes — same engine, same version |
If a test only exercises business logic, mock it. If it exercises SQL, migrations, JSONB, or broker semantics, Testcontainers is the honest answer — and the difference shows up the first time H2 happily parses a query Postgres would have rejected.
Verify the setup actually works
Run one test and watch Docker at the same time:
mvn test -Dtest=PostgresIntegrationTest &
docker ps --format '{{.Image}} {{.Ports}}'
While the suite runs you’ll see postgres:16-alpine with a random host port — that’s the mapped port getMappedPort(5432) reads. If Docker isn’t up, Testcontainers fails fast with Could not find a valid Docker environment before any test executes, which is a much friendlier error than a pile of connection timeouts.
Variants
Using ComposeContainer for multi-service setups
ComposeContainer (added in 1.19.3, replacing the deprecated DockerComposeContainer) boots a whole docker-compose.yml as a test fixture:
@Container
static ComposeContainer<?> compose = new ComposeContainer(
new File("docker-compose-test.yml")
).withExposedService("postgres", 5432)
.withExposedService("redis", 6379);
Reach the services with compose.getServiceHost("postgres", 5432) and compose.getServicePort("postgres", 5432).
Using Network for container-to-container communication
Network network = Network.newNetwork();
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withNetwork(network)
.withNetworkAliases("db");
GenericContainer<?> app = new GenericContainer<>("myapp:latest")
.withNetwork(network)
.withEnv("DB_HOST", "db")
.dependsOn(postgres);
Inside the shared network, containers resolve each other by alias (db:5432), while your test JVM still reaches them through the mapped host ports.
Best Practices
- Use
withReuse(true)andtestcontainers.reuse.enable=truein.testcontainers.propertiesto keep containers between local test runs - Use
staticcontainers with@Container— they start once per test class, not per test - Use
@ServiceConnectionon Spring Boot 3.1+ instead of@DynamicPropertySourceboilerplate - Set a startup timeout for slow images:
withStartupTimeout(Duration.ofMinutes(2)) - Use
withInitScript("init.sql")for schema setup that runs when the container starts; for Flyway/Liquibase, point the migration atgetJdbcUrl()in@BeforeAll - Pull the images in a CI setup step (
docker pull postgres:16-alpine) so the first test never hits a cold-pull timeout
Common Mistakes
- Not using
staticcontainers: non-static containers start and stop per test method, adding 10-30 seconds per test. - Forgetting the Docker requirement: Testcontainers needs a Docker daemon. In CI, use a service with Docker available or Docker socket binding — and verify
docker infoworks before blaming the tests. - Using
latesttags:postgres:latestpoints somewhere different next month and the failure lands on your CI, not in your notes. The fix is boring: pin to a specific version. - No cleanup between tests: a shared container carries state from one method to the next, so test two inherits whatever test one wrote. Roll back with
@Transactional+@Rollback, or truncate tables in@BeforeEach. - Hardcoding mapped ports:
localhost:5432collides with your local Postgres and breaks parallel builds. Always usegetMappedPort(). - Ignoring startup time in the budget: if a test takes 15 seconds and 12 are container startup, switch to a shared static container or reuse mode before blaming the framework.
See Also
- Testcontainers documentation — module list, wait strategies, and reusable-container reference
- Spring Boot: Testing with Testcontainers —
@ServiceConnectionand@Testcontainersintegration - JUnit 5 extension model — the machinery
@Testcontainershooks into - Testcontainers: Real Dependencies in Integration Tests — the long-form companion guide on this site
- Runnable companion project — Maven project with the Postgres, Redis, and Kafka tests from this recipe
Frequently Asked Questions
How do I speed up Testcontainers tests, locally and in CI?
Locally, turn on withReuse(true) + testcontainers.reuse.enable=true and containers survive between runs — the second mvn verify feels like a unit-test suite. In CI the trick is different: share one static container across test classes and pre-pull the images in a setup step, so no test ever pays a cold pull.
Can I run Testcontainers without Docker Desktop?
Yes. On Linux, point at the Docker daemon directly. On macOS and Windows, Colima or Rancher Desktop work as lighter Docker runtimes — Testcontainers only needs a Docker-compatible API.
How do I run schema migrations inside a container?
withInitScript("init.sql") covers simple schemas. For Flyway or Liquibase, start the container, read getJdbcUrl(), and run the migration programmatically in @BeforeAll — the same code path production uses.
What is a wait strategy and when do I need a custom one?
It's the readiness check Testcontainers applies before the first test runs. A port listening or a log pattern is enough for most images; reach for waitingFor(Wait.forHttp("/health")) or Wait.forLogMessage(...) only when a container announces itself before it's actually ready to serve.
Can I use Testcontainers with Kotlin?
Yes — you work with the same API. Use companion object for static containers:
companion object {
@Container
@JvmStatic
val postgres = PostgreSQLContainer("postgres:16-alpine")
}
How do I debug a container that won't start?
Attach withLogConsumer(new Slf4jLogConsumer(logger)) to stream the container's stdout into your test logs — most "won't start" failures are visible there. When the logs look clean, the usual suspects are Docker disk space, an image that failed to pull, and port conflicts.
Can I use Testcontainers with Spring Boot?
Yes, and Spring Boot 3.1+ makes it almost free: add spring-boot-testcontainers and annotate the container with @ServiceConnection — no @DynamicPropertySource needed:
@SpringBootTest
@Testcontainers
class MyIntegrationTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
}
Related Resources
AssertJ Soft Assertions in JUnit5: Collect All Failures
How to use AssertJ soft assertions in JUnit5 to collect multiple assertion failures in a single test instead of stopping at the first failure.
RecipeDesign Effective Integration Tests for Reliable Systems
Write integration tests that verify real component interactions with test containers, API contracts, and consumer-driven contract testing.
RecipeStub External HTTP APIs with WireMock in Java
Use WireMock in Java tests to stub external HTTP services. Covers response templating, delay simulation, stateful stubs, and request verification.
GuideTestcontainers: Real Dependencies in Integration Tests
Master Testcontainers for integration testing with real databases, message brokers, and APIs. Covers Java, Python, and Node.js with Docker-based test fixtures.
GuideJUnit 5: Extensions, Parameterized Tests, Dynamic Tests
Practical JUnit 5 guide: extensions, parameterized and dynamic tests, test interfaces, conditional and parallel execution, and JUnit 4 migration.
RecipeTest Express APIs with supertest
How to test Express.js REST API endpoints end-to-end using supertest, including status codes, JSON bodies, headers, authentication, and error handling.