Testcontainers: real dependencies in Java tests

Testcontainers starts real databases, brokers and other services in throwaway Docker containers from your test code, so integration tests run against the same software as production. This page explains how it finds Docker, starts and waits for containers and cleans up, then shows a JUnit 5 database test, container configuration, shared containers and the 2.0 changes. Docker was not available where the examples ran, and each output says so.

Share

Contents

What Testcontainers does

Integration tests need the real things an application talks to: a database, a message broker, a cache. The traditional substitutes each have a weakness. An in-memory database such as H2 speaks a different SQL dialect and has different locking and constraint behaviour, so tests can pass while production fails. A shared test database is slow to reset, and tests interfere with each other. Testcontainers starts the real software in a throwaway Docker container for the duration of a test, from test code.

Underneath, it is a client of the Docker Engine API, built on the docker-java library. For each container it:

  1. finds a Docker daemon, trying environment variables, the Unix socket, Docker Desktop and rootless Docker in turn;
  2. pulls the image if it is not cached, and creates and starts the container with the configured environment, exposing its ports on random free host ports;
  3. waits until the service is ready, using a wait strategy such as a log message, an open port or a health check, because a running container is not yet an accepting database;
  4. gives the test the mapped host and port, for example through getJdbcUrl();
  5. stops and removes the container afterwards. A small helper container called Ryuk removes anything left behind if the test JVM is killed.

Modules wrap common images with typed classes, such as MariaDBContainer, PostgreSQLContainer or KafkaContainer, which know the right ports, credentials and readiness checks. GenericContainer runs any other image.

Ways to give integration tests a database
ApproachSame behaviour as production?IsolationBest for
In-memory database (H2, HSQLDB)No: different dialect and enginePer test JVMFast tests of simple, portable SQL
A shared test database serverYes, if versions matchPoor: tests share dataLegacy setups
TestcontainersYes: the same image as productionPer class or per suiteRepositories, migrations, vendor-specific SQL
A fake HTTP API (WireMock)Only for HTTPPer testExternal REST services

What was and was not run for this page

The code below was compiled against Testcontainers 1.21.4 and JUnit 5.12, and run on a machine without Docker. The outputs shown are therefore what happens when Docker is missing: the database tests themselves did not execute, and no container was ever started. On a machine with Docker running, the same test classes start MariaDB and run their tests. Everything that does not need Docker, such as configuring containers, the skip behaviour and the error messages, was run for real and is shown with its output.

The code under test

A plain JDBC repository. It uses MariaDB-specific SQL (AUTO_INCREMENT) and relies on a unique constraint, exactly the kind of behavior an in-memory database may not reproduce faithfully.

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Optional;
import javax.sql.DataSource;

// Code under test: plain JDBC that must work against the real database we run in production
public class UserRepository {

    private final DataSource ds;

    public UserRepository(DataSource ds) {
        this.ds = ds;
    }

    public void createSchema() throws SQLException {
        try (Connection c = ds.getConnection(); Statement st = c.createStatement()) {
            st.execute("CREATE TABLE IF NOT EXISTS users (id BIGINT AUTO_INCREMENT PRIMARY KEY, "
                    + "email VARCHAR(100) NOT NULL UNIQUE, name VARCHAR(100))");
        }
    }

    public long save(String email, String name) throws SQLException {
        try (Connection c = ds.getConnection();
             PreparedStatement ps = c.prepareStatement(
                     "INSERT INTO users (email, name) VALUES (?, ?)",
                     Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, email);
            ps.setString(2, name);
            ps.executeUpdate();
            try (ResultSet keys = ps.getGeneratedKeys()) {
                keys.next();
                return keys.getLong(1);
            }
        }
    }

    public Optional<String> findName(String email) throws SQLException {
        try (Connection c = ds.getConnection();
             PreparedStatement ps = c.prepareStatement("SELECT name FROM users WHERE email = ?")) {
            ps.setString(1, email);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next() ? Optional.of(rs.getString(1)) : Optional.empty();
            }
        }
    }
}

The test

@Testcontainers activates the JUnit 5 extension, and @Container marks a container it manages. Because the field is static, one container is started before the first test of the class and stopped after the last; a non-static field would get a fresh container for every test. The container picks a free port and generated credentials, which the test reads with getJdbcUrl(), getUsername() and getPassword().

Java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.sql.SQLIntegrityConstraintViolationException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mariadb.jdbc.MariaDbDataSource;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

// Starts a real MariaDB in Docker for this class; skipped if no Docker is available
@Testcontainers(disabledWithoutDocker = true)
class UserRepositoryTest {

    @Container
    static MariaDBContainer<?> db = new MariaDBContainer<>("mariadb:11.4");

    static UserRepository repo;

    @BeforeAll
    static void setUp() throws Exception {
        MariaDbDataSource ds = new MariaDbDataSource(db.getJdbcUrl());
        ds.setUser(db.getUsername());
        ds.setPassword(db.getPassword());
        repo = new UserRepository(ds);
        repo.createSchema();
    }

    @Test
    void savesAndFindsUsers() throws Exception {
        long id = repo.save("ana@example.com", "Ana");
        assertThat(id).isPositive();
        assertThat(repo.findName("ana@example.com")).contains("Ana");
        assertThat(repo.findName("nobody@example.com")).isEmpty();
    }

    @Test
    void rejectsDuplicateEmail() throws Exception {
        repo.save("ben@example.com", "Ben");
        assertThatThrownBy(() -> repo.save("ben@example.com", "Ben again"))
                .isInstanceOf(SQLIntegrityConstraintViolationException.class);
    }
}

disabledWithoutDocker = true makes the extension skip the class instead of failing when no Docker daemon is reachable. Running it with the launcher from the JUnit 5 page on the Docker-less machine:

Output
SKIP  UserRepositoryTest (disabledWithoutDocker is true and Docker is not available)
tests: 2, passed: 0, failed: 0, aborted: 0, skipped: 2

Without that flag, the class fails. The next program shows the underlying behavior directly:

Java
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.MariaDBContainer;

// What Testcontainers reports on a machine without a Docker daemon
public class NoDocker {

    public static void main(String[] args) {
        System.out.println("Docker available: "
                + DockerClientFactory.instance().isDockerAvailable());
        try (MariaDBContainer<?> db = new MariaDBContainer<>("mariadb:11.4")) {
            db.start();
        } catch (IllegalStateException e) {
            System.out.println("start() failed: " + e.getMessage());
        }
    }
}

Output:

Output
Docker available: false
start() failed: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration

Logging was switched off for these runs to keep the output short; normally Testcontainers logs each way it tried to reach Docker (environment variables, the Unix socket, rootless Docker), which is the place to look when detection fails.

Skipping is right for developer laptops where Docker may be off; in CI, where these tests must run, leave the flag off so a missing Docker daemon fails the build instead of silently skipping coverage.

Configuring containers without starting them

Container objects are configured with fluent with... methods, and much of that configuration can be inspected before anything talks to Docker. The program configures a MariaDB container, tries a private mirror of the image, sets up a Redis container with a wait strategy, and looks up the special jdbc:tc: driver.

Java
import java.sql.Driver;
import java.sql.DriverManager;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.DockerImageName;

// Container objects can be configured and inspected without Docker; only start() needs it
public class ContainerConfig {

    public static void main(String[] args) throws Exception {
        DockerImageName image = DockerImageName.parse("mariadb:11.4");
        System.out.println("image:          " + image.getRepository() + " tag "
                + image.getVersionPart());
        try (MariaDBContainer<?> db = new MariaDBContainer<>(image)
                .withDatabaseName("shop").withUsername("app").withPassword("secret")) {
            System.out.println("database/user:  " + db.getDatabaseName() + " / "
                    + db.getUsername());
            System.out.println("exposed ports:  " + db.getExposedPorts());
            System.out.println("driver class:   " + db.getDriverClassName());
            try {
                db.getJdbcUrl();
            } catch (IllegalStateException e) {
                System.out.println("getJdbcUrl before start(): " + e.getMessage());
            }
        }

        // A private mirror of the image must be declared compatible
        try {
            new MariaDBContainer<>(DockerImageName.parse("registry.example.com/mariadb:11.4"))
                    .close();
        } catch (IllegalStateException e) {
            System.out.println("mirror image: " + e.getMessage().lines().findFirst().orElse(""));
        }
        DockerImageName mirror = DockerImageName.parse("registry.example.com/mariadb:11.4")
                .asCompatibleSubstituteFor("mariadb");
        try (MariaDBContainer<?> ok = new MariaDBContainer<>(mirror)) {
            System.out.println("with asCompatibleSubstituteFor: accepted, database "
                    + ok.getDatabaseName());
        }

        // Any image works with GenericContainer; a wait strategy decides when it is ready
        try (GenericContainer<?> redis = new GenericContainer<>(DockerImageName.parse("redis:7.4"))
                .withExposedPorts(6379)
                .waitingFor(Wait.forLogMessage(".*Ready to accept connections.*", 1))) {
            System.out.println("redis ports:    " + redis.getExposedPorts());
        }

        // The jdbc:tc: URL starts a container on the first connection
        Driver driver = DriverManager.getDriver("jdbc:tc:mariadb:11.4:///shop");
        System.out.println("jdbc:tc: driver: " + driver.getClass().getSimpleName());
    }
}

Output (no Docker available):

Output
image:          mariadb tag 11.4
database/user:  shop / app
exposed ports:  [3306]
driver class:   org.mariadb.jdbc.Driver
getJdbcUrl before start(): Could not find a valid Docker environment. Please see logs and check configuration
mirror image: Failed to verify that image 'registry.example.com/mariadb:11.4' is a compatible substitute for 'mariadb'. This generally means that you are trying to use an image that Testcontainers has not been designed to use. If this is deliberate, and if you are confident that the image is compatible, you should declare compatibility in code using the `asCompatibleSubstituteFor` method. For example:
with asCompatibleSubstituteFor: accepted, database test
redis ports:    [6379]
jdbc:tc: driver: ContainerDatabaseDriver
  • The database name, user, exposed port 3306 and JDBC driver class were all available without Docker; they are plain configuration.
  • getJdbcUrl() was not: it needs the host and the mapped port, so it asked for a Docker environment and failed. With Docker, call it only after the container has started, which the JUnit extension guarantees in @BeforeAll.
  • An image from a private registry was rejected, because the MariaDB module checks that the image is MariaDB. asCompatibleSubstituteFor("mariadb") declares that the mirror is a compatible copy, and the container was accepted. Companies that mirror Docker Hub need this for every module image.
  • GenericContainer took the Redis image, port 6379 and a wait strategy that waits for the log line "Ready to accept connections". Without a wait strategy, tests can connect before the service is listening and fail intermittently.
  • A JDBC URL starting with jdbc:tc: is handled by ContainerDatabaseDriver, which starts a matching container on the first connection. It lets existing code that only takes a URL, such as a Spring application.properties, use Testcontainers without any Java changes.

Sharing one container across test classes

A static @Container field gives one container per test class, so a suite with twenty repository test classes starts twenty databases. The singleton container pattern starts one container for the whole test run, held in a base class. The assumption makes the classes abort cleanly where Docker is missing.

Java
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.BeforeAll;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.MariaDBContainer;

// The singleton pattern: one container for every test class that extends this base class.
// It is started once, on first use, and stopped by Testcontainers' Ryuk sidecar when the JVM ends
public abstract class AbstractDatabaseTest {

    static final MariaDBContainer<?> DB = new MariaDBContainer<>("mariadb:11.4");

    @BeforeAll
    static void startOnce() {
        assumeTrue(DockerClientFactory.instance().isDockerAvailable(), "Docker is not available");
        if (!DB.isRunning()) {
            DB.start();
        }
    }
}
Java
import static org.assertj.core.api.Assertions.assertThat;

import java.sql.Connection;
import java.sql.DriverManager;
import org.junit.jupiter.api.Test;

// One of many test classes sharing the container from AbstractDatabaseTest
class OrderRepositoryIT extends AbstractDatabaseTest {

    @Test
    void databaseIsReachable() throws Exception {
        try (Connection c = DriverManager.getConnection(DB.getJdbcUrl(), DB.getUsername(),
                DB.getPassword())) {
            assertThat(c.isValid(2)).isTrue();
        }
    }
}

Output (no Docker available; the runner was extended to report a class aborted in @BeforeAll):

Output
ABORT OrderRepositoryIT (whole class): Assumption failed: Docker is not available
tests: 1, passed: 0, failed: 0, aborted: 0, skipped: 0
  • The assumption failed in @BeforeAll, so the whole class was aborted and its test never ran or failed. With Docker, the first subclass to run starts the container and every later one finds it running.
  • The base class deliberately has no @Testcontainers or @Container: the extension would stop the container after each class. Ryuk removes it when the JVM exits.
  • Because all classes share one database, each test must leave it clean, for example by truncating tables in @BeforeEach or by running inside a rolled-back transaction.

Practical points

  • Pin image versions: mariadb:11.4, not latest, so a new image release does not change test results overnight. Use the version you run in production.
  • Start-up cost: the first run downloads the image, and each container start takes seconds. Share containers per class (static fields) or per test suite (a singleton started once in a base class), and isolate tests with transactions or by cleaning tables.
  • Classpath: while preparing this page, a missing runtime dependency made Testcontainers report "Docker is not available" even though the real problem was a NoClassDefFoundError. Use the Testcontainers BOM with Maven or Gradle so all transitive dependencies are present.
  • Spring Boot: since Spring Boot 3.1, @ServiceConnection on a container field wires its connection details into the application context automatically, replacing @DynamicPropertySource boilerplate.

Testcontainers 2.0

Testcontainers 2.0, released on 14 October 2025, makes these breaking changes according to its GitHub release notes:

Changes in Testcontainers 2.0
Area1.x2.0
Module artifactsorg.testcontainers:mariadborg.testcontainers:testcontainers-mariadb (a testcontainers- prefix on every module)
Container classesorg.testcontainers.containers.MariaDBContainerPer-module packages, such as org.testcontainers.mariadb
JUnit 4Supported (@Rule, @ClassRule)Removed; use the JUnit 5 extension
Module constructorsNo-argument constructors with a default imageRemoved: pass the image name explicitly, as this page already does

The test structure on this page (@Testcontainers, @Container, a static container field) stays the same; mainly imports and dependency names change. The code above was not compiled against 2.0.

Choosing a setup

Testcontainers options
SituationUse
One test class needs a databaseA static @Container field with @Testcontainers
Many classes need the same databaseA singleton container in a base class
Code that only accepts a JDBC URLA jdbc:tc: URL
An image without a moduleGenericContainer with a wait strategy
Images from a private registryasCompatibleSubstituteFor, or a configured image name substitutor
Laptops where Docker may be offdisabledWithoutDocker = true or an assumption
CI, where the tests must runNo skip flag, so a missing Docker daemon fails the build
Spring Boot 3.1 or later@ServiceConnection on the container field