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.
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:
- finds a Docker daemon, trying environment variables, the Unix socket, Docker Desktop and rootless Docker in turn;
- 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;
- 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;
- gives the test the mapped host and port, for example through
;getJdbcUrl() - 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 MariaDBContainerPostgreSQLContainerKafkaContainerGenericContainer
| Approach | Same behaviour as production? | Isolation | Best for |
|---|---|---|---|
| In-memory database (H2, HSQLDB) | No: different dialect and engine | Per test JVM | Fast tests of simple, portable SQL |
| A shared test database server | Yes, if versions match | Poor: tests share data | Legacy setups |
| Testcontainers | Yes: the same image as production | Per class or per suite | Repositories, migrations, vendor-specific SQL |
| A fake HTTP API ( | Only for HTTP | Per test | External 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
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@ContainerstaticgetJdbcUrl()getUsername()getPassword()
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
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:
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:
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...jdbc:tc:
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):
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.
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 ingetJdbcUrl() .@BeforeAll- An image from a private registry was rejected, because the MariaDB module checks that the image is 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.asCompatibleSubstituteFor("mariadb") 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.GenericContainer- A JDBC URL starting with
is handled byjdbc:tc: , which starts a matching container on the first connection. It lets existing code that only takes a URL, such as a SpringContainerDatabaseDriver , use Testcontainers without any Java changes.application.properties
Sharing one container across test classes
A static @Container
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();
}
}
}
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
ABORT OrderRepositoryIT (whole class): Assumption failed: Docker is not available
tests: 1, passed: 0, failed: 0, aborted: 0, skipped: 0
- The assumption failed in
, 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.@BeforeAll - The base class deliberately has no
or@Testcontainers : the extension would stop the container after each class. Ryuk removes it when the JVM exits.@Container - Because all classes share one database, each test must leave it clean, for example by truncating tables in
or by running inside a rolled-back transaction.@BeforeEach
Practical points
- Pin image versions:
, notmariadb:11.4 , so a new image release does not change test results overnight. Use the version you run in production.latest - 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
. Use the Testcontainers BOM with Maven or Gradle so all transitive dependencies are present.NoClassDefFoundError - Spring Boot: since Spring Boot 3.1,
on a container field wires its connection details into the application context automatically, replacing@ServiceConnection boilerplate.@DynamicPropertySource
Testcontainers 2.0
Testcontainers 2.0, released on 14 October 2025, makes these breaking changes according to its GitHub release notes:
| Area | 1.x | 2.0 |
|---|---|---|
| Module artifacts | org.testcontainers:mariadb | org.testcontainers:testcontainers-mariadbtestcontainers- |
| Container classes | org.testcontainers.containers.MariaDBContainer | Per-module packages, such as org.testcontainers.mariadb |
| JUnit 4 | Supported (@Rule@ClassRule | Removed; use the JUnit 5 extension |
| Module constructors | No-argument constructors with a default image | Removed: pass the image name explicitly, as this page already does |
The test structure on this page (@Testcontainers@Container
Choosing a setup
| Situation | Use |
|---|---|
| One test class needs a database | A static @Container@Testcontainers |
| Many classes need the same database | A singleton container in a base class |
| Code that only accepts a JDBC URL | A jdbc:tc: |
| An image without a module | GenericContainer |
| Images from a private registry | asCompatibleSubstituteFor |
| Laptops where Docker may be off | disabledWithoutDocker = true |
| CI, where the tests must run | No skip flag, so a missing Docker daemon fails the build |
| Spring Boot 3.1 or later | @ServiceConnection |