Integration testing with Testcontainers

Mid-level Frequently asked 4 min

On this page

The question

Why not use H2 for integration tests?

30-second answer

Because H2 is not your production database. Its SQL dialect, types, functions and locking differ, so a test can fail on valid PostgreSQL, or pass on SQL that production rejects. PostgreSQL features such as jsonb operators, extensions or your real migration scripts may not run at all. Testcontainers runs the same engine and version as production in Docker, at the cost of a few seconds of startup.

Understand it

A container around a test class

Step by step

@Testcontainers is a JUnit 5 extension. Before any test runs, it finds the static @Container field in the test class.

Step 1 of 6
View as text

Two panels side by side. The JVM holds the test class and the Spring context. Docker holds the Ryuk helper and a PostgreSQL container. A line below shows the host port mapping, and a mark gives the current status.

@Testcontainers is a JUnit 5 extension. Before any test runs, it finds the static @Container field in the test class.

Testcontainers asks Docker for the postgres:16 image, pulling it if needed. A small helper container, Ryuk, starts too, to clean up later.

It waits until PostgreSQL really accepts connections, and Docker maps port 5432 to a random free port on the host, so parallel runs never clash. The mapping reads localhost, random port, to 5432.

@ServiceConnection gives Spring the URL, user and password of that container. Only then does the application context start and connect. An arrow joins the Spring context to PostgreSQL.

Every test talks to real PostgreSQL. A static container is shared by the class, so one test can see rows another left behind. Clean up between tests.

After the last test, the container is stopped and removed. If the JVM dies first, Ryuk notices and removes it, so nothing is left running. The PostgreSQL box fades as removed.

Two panels side by side. The JVM holds the test class and the Spring context. Docker holds the Ryuk helper and a PostgreSQL container. A line below shows the host port mapping, and a mark gives the current status.

@Testcontainers is a JUnit 5 extension. Before any test runs, it finds the static @Container field in the test class.

Testcontainers asks Docker for the postgres:16 image, pulling it if needed. A small helper container, Ryuk, starts too, to clean up later.

It waits until PostgreSQL really accepts connections, and Docker maps port 5432 to a random free port on the host, so parallel runs never clash. The mapping reads localhost, random port, to 5432.

@ServiceConnection gives Spring the URL, user and password of that container. Only then does the application context start and connect. An arrow joins the Spring context to PostgreSQL.

Every test talks to real PostgreSQL. A static container is shared by the class, so one test can see rows another left behind. Clean up between tests.

After the last test, the container is stopped and removed. If the JVM dies first, Ryuk notices and removes it, so nothing is left running. The PostgreSQL box fades as removed.

Takeaway: Testcontainers starts a real, throwaway database in Docker before the tests, gives Spring its random port, and removes it afterward, even after a crash.

H2 or a real database in a containerIf the test is about SQL, migrations or database features, run the real engine in a container. If it only needs somewhere to store rows, H2 can be enough. If it needs no database at all, use a plain unit test with a fake.What does thetest rely on?SQL, migrations,engine features:containerOnly stored rows:H2 can doNo database:unit test, fake
H2 or a real database in a containerIf the test is about SQL, migrations or database features, run the real engine in a container. If it only needs somewhere to store rows, H2 can be enough. If it needs no database at all, use a plain unit test with a fake.What does thetest rely on?SQL, migrations,engine features:containerOnly stored rows:H2 can doNo database:unit test, fake
H2 or a real database in a container

In code

@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
    @Container                 // static: one container, shared by every test in the class
    @ServiceConnection         // Boot 3.1+: Spring gets the URL, user and password
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @Autowired OrderRepository orders;

    @Test
    void savesAnOrder() {
        orders.save(new Order("ana", 20));
        assertEquals(1, orders.count());
    }
}
One real PostgreSQL for the whole test class
@DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
}
Without @ServiceConnection: pass the random port yourself
What happens around OrderRepositoryITThe extension finds the static container field and starts PostgreSQL in Docker. It waits until the database is ready on a random host port. Spring starts with that URL, the tests run against it, and the container is removed at the end.Extension findsthe static@ContainerDocker startspostgres:16Ready on a randomportSpring starts withthat URLTests run real SQLContainer removed
What happens around OrderRepositoryITThe extension finds the static container field and starts PostgreSQL in Docker. It waits until the database is ready on a random host port. Spring starts with that URL, the tests run against it, and the container is removed at the end.Extension findsthe static@ContainerDocker startspostgres:16Ready on a randomportSpring starts withthat URLTests run real SQLContainer removed
What happens around OrderRepositoryIT
@SpringBootTest
@Testcontainers
class OrderEventsIT {
    @Container
    @ServiceConnection
    static KafkaContainer kafka = new KafkaContainer("apache/kafka-native:3.8.0");

    @Autowired KafkaTemplate<String, String> kafkaTemplate;

    @Test
    void publishesOrderPlaced() throws Exception {
        kafkaTemplate.send("orders", "42", "PLACED").get(10, TimeUnit.SECONDS);   // acknowledged by a real broker
    }
}
Not only databases: a Kafka broker for one test class

Solve it

Integration tests take 6 minutes because every class starts its own database

Forty integration test classes each declare @Container static PostgreSQLContainer. Each class starts and stops PostgreSQL, about 5 seconds per class before any test runs. Make the database start once without making tests depend on each other.

  1. Measure. Forty classes times about five seconds is over three minutes of startup alone.
  2. Know the lifecycle. A static @Container field lives for one test class: started before it, stopped after it.
  3. Share one container. Start it once in a static block of an abstract base class. Testcontainers’ Ryuk container removes it when the JVM (Java Virtual Machine) exits.
  4. Keep tests isolated. The database is now shared, so each test cleans up: roll back with @Transactional on the test, or truncate tables in @AfterEach.
  5. Check. docker ps during the run shows one PostgreSQL, and the suite passes in any order.
abstract class PostgresTestBase {
    static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16");
    static { POSTGRES.start(); }                       // once per JVM, removed by Ryuk at exit

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

@SpringBootTest
@Transactional                                         // each test rolls back its rows
class OrderRepositoryIT extends PostgresTestBase { /* tests */ }
One PostgreSQL for the whole test run

How to answer

  • PostgreSQL mode in H2 is an approximation, not the real engine.
  • Flyway or Liquibase scripts get tested against the real engine too.
  • Sharing one container per test class or suite keeps the cost low.

Common mistakes

  • Trusting a green H2 suite to prove that native queries work in production.
  • Writing SQL only to what H2 accepts, which hides real features of the database.

Follow-up questions

How do Testcontainers work?

It is a Java library that drives Docker from your tests. Before the tests, it pulls the image if needed, starts the container, waits until the service is really ready, and maps its port to a random free host port. Your test reads the real address from the container object. Afterward it removes the container, and a helper called Ryuk removes anything left behind if the JVM dies.

  • Random ports let many builds run on one machine with no clashes.
  • A wait strategy, not a fixed sleep, decides when the container is ready.
  • It has modules for databases, Kafka and more, plus GenericContainer for any image.

See it in the infographic: A container around a test class

What is the difference between a static and a non-static @Container field?

A static field gives one container, started before the first test and stopped after the last in that class, so tests share it and its data. An instance field gives each test method its own new container: clean but slow. For a whole suite, the singleton container pattern starts one in a static initializer of a base class and never stops it, leaving cleanup to Ryuk.

  • Shared containers mean tests must clean up or use unique data.
  • @Transactional tests can roll back their writes in a shared container.
  • With a singleton container, Spring's context cache can also be reused across classes.

See it in the infographic: A container around a test class

The container's port is random. How does Spring Boot find it?

Since Spring Boot 3.1, @ServiceConnection on the container field does it for you: Boot reads the connection details from the container. Before that, @DynamicPropertySource registers spring.datasource.url and the rest from the container's getters. Either way the container must be running before the context starts, which a static @Container field guarantees.

  • getJdbcUrl() returns the URL with the mapped host port.
  • Hard-coding a port would break parallel builds.
  • The method references are read lazily, once the container has started.
@DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
}

See it in the infographic: A container around a test class

When is H2 still acceptable?

When the test does not depend on the engine: simple generated queries in a project with no native SQL, or a quick local slice on a machine with no Docker. It starts faster and needs no setup. The risk grows with every native query or engine feature you add, so many teams move those tests to containers.

What does Testcontainers need in CI (continuous integration)?

A Docker-compatible daemon the tests can reach. On a CI runner that is usually Docker itself, or a remote Docker host when the job has no local daemon. Pulling images takes time, so caching them helps. Some locked-down environments must also disable Ryuk, because it needs privileged access to the Docker socket.

Check yourself

1. A test class has three test methods and one static @Container field. How many containers start for that class?
Show answers
  • One: Correct. A static field is shared, so the extension starts it once for the whole class.
  • Three: Incorrect. That is what a non-static field gives, one per test method.
  • Four, one extra for the class: Incorrect. There is one field, so there is one database container.
2. Why does Testcontainers map the container's port to a random host port?
Show answers
  • So several containers and builds can run on one machine: Correct. A fixed port would clash with a local database or a parallel build.
  • To hide the database from attackers: Incorrect. It is about avoiding clashes; a test database is short-lived and holds no real data.
  • Because PostgreSQL cannot listen on port 5432 in Docker: Incorrect. Inside the container it still listens on 5432; only the host side is random.