Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 66 ยท Testing

Integration Tests with Testcontainers

Test against real PostgreSQL, Redis or Kafka from Spring Boot with Testcontainers: @ServiceConnection, dynamic properties, reuse and CI tips.

An in-memory database is convenient, and it lies. H2 accepts SQL that PostgreSQL rejects, rejects SQL that PostgreSQL accepts, has different locking, different date handling, no jsonb, no partial indexes, and none of your production extensions. A test that passes on H2 and fails in production is worse than no test, because it gave you confidence you did not deserve.

Testcontainers solves that by starting the real database (or broker, or cache) in a throwaway Docker container for the duration of your tests. Spring Boot has first-class support: with @ServiceConnection a container is wired into the application with almost no configuration, and the same container definition can even power your local development. This lesson shows how it works, how to share and reuse containers, and what to watch for in CI. For the library itself, see Testcontainers.

This lesson is read-only for the real code: it needs a Docker daemon, which this site cannot provide. The TryIts show the two ideas that matter most, inside plain Java: values that only exist after a container starts, and one container shared by many test classes.

Why real services in tests

Fakes differ H2 is not PostgreSQL.
Dialect bugs Fail in production, not in tests.
Real versions Pin the same image tag you deploy.
Disposable A clean container for every run.
1 / 2

The smallest working setup

Add the dependencies (Testcontainers' JUnit integration, the database module, and Boot's support, which is part of spring-boot-testcontainers):

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-testcontainers</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>

Artifact names changed in Testcontainers 2 (the database modules are now prefixed, for example testcontainers-postgresql), which is what Boot 4 uses; the Initializr adds the right ones when you tick "Testcontainers". Then write the test:

Java
@SpringBootTest
@Testcontainers
class OrderRepositoryIT {

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

    @Autowired
    OrderRepository orders;

    @Test
    void savesAndFindsAnOrder() {
        var saved = orders.save(new Order("book-1", 2));

        assertThat(orders.findById(saved.getId())).isPresent();
    }
}

Four things happen here:

  1. @Testcontainers and @Container tell JUnit to start the container before the tests and stop it afterwards. The field is static, so one container serves all tests in the class; a non-static field would start a fresh container for every test method.
  2. postgres:17-alpine pins the image. Use the same major version as production, never latest.
  3. @ServiceConnection tells Boot to read the container's JDBC URL, username and password and configure the DataSource from them. You write no spring.datasource.* properties for the test.
  4. The application context starts as usual, now talking to a real PostgreSQL on a random mapped port.

@ServiceConnection is supported for the common services: PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch, Cassandra and more. For a container type Boot does not know, or for a custom property, use dynamic properties.

Dynamic properties: values that exist only after start

A container publishes its service on a random free host port, chosen when it starts. So the connection URL cannot be written in application.yml; it does not exist until the container is up. @DynamicPropertySource solves this by registering properties as suppliers that Spring calls later, when it needs them:

Java
@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
    registry.add("spring.data.redis.host", redis::getHost);
    registry.add("spring.data.redis.port", () -> redis.getMappedPort(6379));
    registry.add("app.mail.base-url", () -> "http://" + mailpit.getHost() + ":" + mailpit.getMappedPort(8025));
}

Because the values are method references or lambdas, they are evaluated after the container has started. Writing redis.getHost() directly as the second argument would call it too early and fail. The TryIt shows the idea with a stand-in "container" that really opens a free port on your machine's loopback interface (inside the sandbox) and a registry that resolves suppliers lazily.

Java Properties that only exist after start

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.

What is real: ports are random, and values must be supplied lazily. What is the stand-in: a real Testcontainers container starts a Docker image, waits until the service is ready (using a wait strategy), and maps the container port to a free host port through the Docker daemon.

Sharing one container across many test classes

Starting PostgreSQL takes a couple of seconds. If every test class starts its own container, a large suite spends minutes on startup alone. Three techniques keep that under control:

A shared static container. Declare the container once in an abstract base class, or in a configuration class, and start it manually. All test classes then share one container (and, through Spring's context cache, one application context):

Java
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {

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

@SpringBootTest
@Import(ContainersConfig.class)
class OrderRepositoryIT { ... }

Declaring the container as a bean with @ServiceConnection is the modern Boot style: Spring starts it with the context and stops it when the context closes. Because every test class that imports ContainersConfig produces the same context, the container starts once. You can also run the application locally against the same containers, using a TestMyApplication class with SpringApplication.from(MyApplication::main).with(ContainersConfig.class).run(args), so a developer needs only Docker, not an installed database.

Isolation by cleanup, not by restarting. A shared container means shared data. Give each test a clean slate by using @Transactional tests that roll back, truncating tables in @BeforeEach, or using unique keys per test. Tests must never depend on each other's rows.

Reusable containers. With .withReuse(true) on the container and testcontainers.reuse.enable=true in ~/.testcontainers.properties, Testcontainers keeps the container running between runs on your machine, so the second run of the suite skips startup. Use this for local speed only; on CI start fresh containers for every build so that old state cannot hide a problem.

The next TryIt models the second technique with the real H2 database: one "container" starts once, three "test classes" share it, and each cleans up before it runs.

Java One shared database, clean state per test

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 start counter stays at 1 while each class sees only its own rows. What is real: share an expensive resource, reset the data. What is the stand-in: H2 inside this program replaces a Docker container.

Other services and practical details

The same pattern works for any service. A Kafka or Redis test uses KafkaContainer or RedisContainer with @ServiceConnection; a generic container uses GenericContainer with withExposedPorts(...) and dynamic properties. Beyond databases, Testcontainers can start an S3 emulator (LocalStack), a mail catcher, a Keycloak identity provider or even a Selenium browser.

Run your schema migrations against the container: Flyway runs at context startup as usual, so the test exercises the real migration scripts. That is one more thing H2 cannot do faithfully, and a good reason to use the production engine.

Things that cause trouble in practice:

  • Docker must be available. Local machines need Docker Desktop, Colima or Podman; CI runners need a Docker socket. Without it tests fail at startup. Some teams mark container tests with a JUnit tag (@Tag("integration")) and run them in a separate Maven phase (Failsafe, *IT classes) so quick feedback loops stay Docker-free.
  • Wait strategies. A container is "started" when its process runs, not when the service is ready. Built-in modules wait correctly. For a GenericContainer, add .waitingFor(Wait.forListeningPort()) or Wait.forLogMessage(...).
  • Resource limits. Several databases at once need real memory. On CI, reuse one container for many classes rather than one per class.
  • Pull time. The first run downloads images. Cache them on CI runners, and pull from a registry mirror if rate limits bite.
  • Ryuk. Testcontainers starts a small cleanup container that removes leftovers if the JVM crashes. Some locked-down CI systems need extra setup for it; check their documentation rather than disabling it blindly.
  • Do not test everything this way. Container tests are slower than slices. Use them for repositories, migrations and integration seams; keep business logic in plain unit tests (see Testing Spring Boot Applications).

For repository tests you can combine the data slice with a container: @DataJpaTest plus @AutoConfigureTestDatabase(replace = Replace.NONE) and a @ServiceConnection container tests your queries against the real engine without loading the web layer. Testing the Data Layer covers that setup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a test that passes against H2 still fail against production PostgreSQL?

    An in-memory database is a different product that imitates another one. Running the production engine in a container removes that gap.
  2. 2. What does @ServiceConnection on a container do?

    Instead of writing spring.datasource.* for tests, Boot derives URL, username and password from the container itself.
  3. 3. Why must container-derived values be registered as suppliers (for example redis::getHost) in a DynamicPropertyRegistry?

    The mapped port is chosen when the container starts. A supplier defers the call until Spring needs the value.
  4. 4. Which approach shortens a suite that has twenty test classes needing PostgreSQL?

    Sharing the container and context avoids repeated startup, and cleaning data keeps tests independent.

Summary

  • Testcontainers runs the real database or broker in Docker for your tests, removing the gap between H2 and production.
  • @ServiceConnection lets Boot configure the application from the container; declare containers as beans in a @TestConfiguration for the cleanest setup.
  • Mapped ports are random, so use @DynamicPropertySource with suppliers for custom properties.
  • Share containers across test classes, reset data between tests, and use reusable containers only for local speed.
  • Pin image tags to your production version, run real migrations, and keep Docker-dependent tests separate if fast feedback matters.
  • Use containers for repositories and integration seams, not for logic that a plain unit test can check.

Next: Test Slices, Context Caching and Test Speed.