StackPractices
advanced By Mathias Paulenko

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:

Testcontainers startup: the JUnit 5 extension finds @Container fields, boots them with Docker, and assigns random host ports

Once the container is up, readiness and cleanup are automatic too:

Testcontainers lifecycle: a wait strategy confirms readiness, tests run against the real service, and the Ryuk reaper removes everything

Three details matter more than the API surface:

  • Mapped ports are random. Never hardcode localhost:5432 — ask the container with getHost() and getMappedPort(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?

PatternLifecycleStartup costWhen to pick it
@Container staticOnce per test classOne startup per classDefault for almost everything
@Container (instance)Once per test methodFull startup per testWhen each test needs a pristine container
withReuse(true)Survives across runs~0 after the first runLocal 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?

ApproachFidelitySpeedCatches real DB issues
Mockito mocksNone (you fake the answers)FastestNever
H2 / embeddedMedium (different dialect)FastSometimes — MODE=PostgreSQL helps but isn’t Postgres
TestcontainersReal service5-15s startupYes — 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) and testcontainers.reuse.enable=true in .testcontainers.properties to keep containers between local test runs
  • Use static containers with @Container — they start once per test class, not per test
  • Use @ServiceConnection on Spring Boot 3.1+ instead of @DynamicPropertySource boilerplate
  • 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 at getJdbcUrl() 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 static containers: 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 info works before blaming the tests.
  • Using latest tags: postgres:latest points 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:5432 collides with your local Postgres and breaks parallel builds. Always use getMappedPort().
  • 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

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");
}