Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 119 ยท Testing

Integration Tests with Testcontainers

Run integration tests against real PostgreSQL, Redis or Kafka in throwaway Docker containers, covering lifecycle, wait strategies, Spring Boot ServiceConnection, speed and CI tips.

An in-memory database such as H2 makes tests fast, but it is not the database you run in production. SQL that works on H2 can fail on PostgreSQL, and the reverse is just as common. The same problem appears with message brokers, caches, search engines and any other infrastructure: a fake behaves almost like the real thing, until the day it does not.

Testcontainers is a Java library that closes this gap. From inside a JUnit test it starts the real service (PostgreSQL, MySQL, Redis, Kafka, RabbitMQ, Elasticsearch, or any Docker image) in a throwaway Docker container, hands your code the address, and removes the container when the tests end. Integration Testing introduced the idea and showed the shortest possible example. This lesson goes deeper: how the lifecycle works, how Testcontainers knows a container is ready, how Spring Boot connects to it with almost no configuration, and how to keep a suite of container tests fast.

The runner on this site has no Docker, so the Testcontainers code below is read-only. The runnable examples rebuild the key mechanics (readiness waiting and container lifecycle) with plain Java and a small stand-in "container", so you can see why the real library is designed the way it is.

What happens during a test run

sequenceDiagram
  participant T as JUnit test
  participant L as Testcontainers library
  participant D as Docker daemon
  participant C as postgres container
  T->>L: container.start()
  L->>D: pull image if missing, create container with a random host port
  D->>C: start process
  L->>C: wait strategy: poll until the database accepts connections
  L-->>T: getJdbcUrl() with host and mapped port
  T->>C: run SQL through the normal JDBC driver
  T->>L: end of test class or JVM exit
  L->>D: stop and remove the container

The test talks to the real database through its normal driver; Testcontainers only manages the container around it.

Three details of this flow matter in practice:

  • Random ports. The container's port 5432 is published on a random free port on your machine. You must never hard-code localhost:5432; ask the container (getJdbcUrl(), or getHost() and getMappedPort(5432)). This lets several builds run in parallel on one machine without clashes.
  • Readiness. "Container started" does not mean "database ready". PostgreSQL needs a moment to initialize. Each container type has a wait strategy that polls until the service really answers, so your test does not begin with a connection error.
  • Cleanup. A small helper container named Ryuk watches your test JVM and deletes the containers if the JVM dies, even after a crash or kill -9, so nothing is left running.

Setup

You need Docker (Docker Desktop, Colima, Podman with its Docker API, or a CI runner with Docker) available to the build. Add the dependencies with test scope. With Testcontainers 2.x the modules have a testcontainers- prefix:

XML
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>testcontainers-junit-jupiter</artifactId>
  <version>2.0.5</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>testcontainers-postgresql</artifactId>
  <version>2.0.5</version>
  <scope>test</scope>
</dependency>

Name integration test classes *IT and run them with the Failsafe plugin, as shown in Integration Testing, so that mvn test stays quick and Docker is only needed for mvn verify.

Waiting until the container is ready

The simplest wait strategy checks whether a port accepts connections. The next example does it for real over loopback. A stand-in "service" opens its port only after a delay, like a database booting. A client that connects immediately is refused, a client that follows a wait strategy (poll every 50 ms, give up after a timeout) succeeds, and a service that never starts produces a clear timeout error instead of a mysterious failure later:

Java A wait strategy for a slow-starting service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real Testcontainers offers richer strategies, which you set with waitingFor(...) on any container:

Java
GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379)
        .waitingFor(Wait.forLogMessage(".*Ready to accept connections.*\\n", 1))
        .withStartupTimeout(Duration.ofSeconds(60));

GenericContainer<?> api = new GenericContainer<>("example/api:1.4")
        .withExposedPorts(8080)
        .withEnv("MODE", "test")
        .waitingFor(Wait.forHttp("/actuator/health").forStatusCode(200));

Typed containers such as PostgreSQLContainer come with a sensible strategy built in (they wait until a test query succeeds), so you only choose one for generic images. Never replace the strategy with Thread.sleep(5000): it is slow on a fast machine and flaky on a slow CI server.

The container lifecycle in JUnit

With the JUnit 5/6 extension, a field annotated @Container inside a class annotated @Testcontainers is managed for you. Where you declare the field decides how often the container starts:

  • A static field starts once before the first test of the class and stops after the last one. This is the normal choice.
  • An instance field starts a fresh container before every test method. Isolation is perfect, but each start costs seconds.

A third pattern is the singleton container: start the container once for the whole test run (for example in a static initializer of a shared base class) and let all test classes share it. Testcontainers' Ryuk helper removes it when the JVM ends. A suite with twenty test classes then pays the startup cost once instead of twenty times.

Sharing a container means tests can see each other's data, so you need a cleaning strategy: truncate tables in @BeforeEach, roll back a transaction after each test, or use a unique schema or ids per test. The runnable example below makes all of this visible. FakeDatabaseContainer is a stand-in with the same start/stop/getJdbcUrl shape as a real container, backed by H2 and counting how often it is "started". Real JUnit tests run through the launcher, as in JUnit Basics, and the output compares the lifecycle choices:

Java Container lifecycles compared with real JUnit tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The numbers tell the story. Three tests with a per-test container start three containers; the static field starts one; two whole test classes sharing a singleton start one in total. The last run shows the price of sharing without cleaning: startsEmpty fails because the earlier test's row is still there. In a real suite that kind of failure depends on test order, which makes it hard to reproduce; cleaning in @BeforeEach is cheap insurance.

Connecting a Spring Boot application

Your application normally reads the database address from spring.datasource.url. With a random port, the address is not known until the container has started. There are two ways to hand it over.

The older way is @DynamicPropertySource, which registers properties computed at runtime:

Java
@SpringBootTest
@Testcontainers
class BookRepositoryIT {

    @Container
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    @DynamicPropertySource
    static void datasource(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired BookRepository books;

    @Test
    void findsBooksByTitlePrefix() {
        books.save(new Book("Dune"));
        assertThat(books.findByTitleStartingWith("Du")).hasSize(1);
    }
}

Spring Boot 3.1 and later has a better way, @ServiceConnection. Boot recognizes the container type and wires every matching property (JDBC URL, credentials, or a Redis host and port) itself:

Java
@SpringBootTest
@Testcontainers
class BookRepositoryIT {

    @Container
    @ServiceConnection
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    // no @DynamicPropertySource needed
}

@ServiceConnection also works for Redis, Kafka, RabbitMQ, MongoDB, Elasticsearch and more. When several test classes should share one set of containers, declare them once as beans in a configuration class and import it:

Java
@TestConfiguration(proxyBeanMethods = false)
class TestContainersConfig {

    @Bean
    @ServiceConnection
    PostgreSQLContainer postgres() {
        return new PostgreSQLContainer("postgres:17-alpine");
    }

    @Bean
    @ServiceConnection(name = "redis")
    GenericContainer<?> redis() {
        return new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);
    }
}

@SpringBootTest
@Import(TestContainersConfig.class)
class OrderFlowIT { /* ... */ }

Spring's test context cache reuses the application context across classes that use the same configuration, so the containers start once. The same configuration also powers local development: a TestApplication class in src/test/java that calls SpringApplication.from(Application::main).with(TestContainersConfig.class).run(args) starts your app with a throwaway PostgreSQL and Redis, with no manual Docker commands. Flyway migrations run against the container at startup, so the integration test exercises your real schema scripts, and Spring Data Redis code is tested against a real Redis. See Spring Boot Testing for the surrounding test slices.

Useful features

  • Init scripts. new PostgreSQLContainer("postgres:17-alpine").withInitScript("schema.sql") runs a classpath script after startup. Prefer your real migration tool so tests and production share the same schema.
  • Networks. For multi-container setups, create Network.newNetwork(), attach containers with withNetwork(network) and withNetworkAliases("db"), and let them talk to each other by alias.
  • Copying files and logs. withCopyFileToContainer(MountableFile.forClasspathResource("conf.yml"), "/etc/app/conf.yml") ships configuration in, and container.getLogs() or a Slf4jLogConsumer brings logs out when a test fails.
  • Reuse. withReuse(true) plus testcontainers.reuse.enable=true in ~/.testcontainers.properties keeps containers alive between runs on your laptop for fast reruns. Use it for local development only, never on CI.
  • Skipping without Docker. @Testcontainers(disabledWithoutDocker = true) skips the class instead of failing when Docker is not installed.

Making container tests fast and reliable

  1. Pin image versions (postgres:17-alpine, never latest) and match the version you run in production.
  2. Start containers as rarely as possible: static fields, shared configuration or a singleton, and one Spring context per configuration.
  3. Keep a fast layer below. Unit tests with mocks (Mocking) should cover the logic; container tests should cover the integration points: SQL, serialization, transactions and message handling. A pyramid with many unit tests and some integration tests keeps feedback quick.
  4. Clean data deliberately (truncate, rollback, or per-test ids) and never rely on test order.
  5. Prepare CI. GitHub Actions' Ubuntu runners and most Docker-capable runners work out of the box. If your CI itself runs in a container, mount the Docker socket instead of running Docker-in-Docker, and cache or pre-pull images to avoid rate limits.
  6. Prefer waiting on the right signal. Use the default strategy of typed containers or a log or HTTP check, never fixed sleeps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a test never hard-code localhost:5432 for a Testcontainers database?

    Random ports let parallel builds and local services coexist. Use getJdbcUrl() or getHost() and getMappedPort().
  2. 2. What is the difference between a static and an instance field annotated with @Container?

    Instance containers give perfect isolation at the price of a startup per test, so static fields are the usual choice.
  3. 3. What does a wait strategy do?

    A started container is not necessarily a ready service. Wait strategies check a port, a log line or an HTTP endpoint.
  4. 4. What does @ServiceConnection on a container field give you in Spring Boot?

    It replaces the @DynamicPropertySource boilerplate for supported services such as PostgreSQL, Redis and Kafka.
  5. 5. Several test classes share one singleton container. What must you add to keep tests independent?

    A shared container keeps its data. The leaky example in the lesson fails because an earlier test's row stayed behind.

Summary

  • Testcontainers starts real services in disposable Docker containers from your tests, on random ports, and removes them afterwards (Ryuk guarantees cleanup).
  • Always read the address from the container, and rely on a wait strategy (port, log line or HTTP check) rather than sleeping.
  • A static @Container starts once per class, an instance field once per test, and a singleton or shared Spring configuration once per run; shared containers need data cleaning.
  • With Spring Boot, @ServiceConnection wires datasource, Redis, Kafka and other connections automatically; a @TestConfiguration with container beans can also power local development.
  • Pin image versions, keep unit tests as the fast base of the pyramid, run container tests in Failsafe, and plan Docker access for CI.

Next: Logging Frameworks covers how to see what your application is doing, in tests and in production.