Skip to content
javahacks.dev
Testing

How to Use Testcontainers for Databases in Java Tests

Run real PostgreSQL or MySQL in Java tests with Testcontainers: dependencies, JUnit extension, JDBC URL, migrations, performance tips and Docker requirements.

6 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the OpenJDK, Hibernate, Jenkins and Cucumber logos.

A test that runs against an in-memory database proves that your code works with that in-memory database. Production runs PostgreSQL or MySQL, with different SQL dialects, different locking, different types and different error messages, so a green test can hide a failing query. Testcontainers closes the gap by starting the real engine in a throwaway Docker container for the duration of the tests. This post sets up PostgreSQL 17 with JUnit 5, covers the parts that cause trouble, and shows the Spring Boot shortcut. Docker must be running on the machine that executes the tests, which is the one real requirement.

Dependencies

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

Check the Testcontainers site for the current version and artifact names before copying these, because a newer major release renamed the modules with a testcontainers- prefix. If you use Spring Boot, import the Testcontainers BOM, or let Boot's dependency management supply the version, so the modules stay in step with each other. The PostgreSQL JDBC driver must also be on the test classpath.

A first test

java
@Testcontainers
class OrderRepositoryTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Test
    void savesAndReadsAnOrder() throws Exception {
        try (Connection c = DriverManager.getConnection(
                postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) {
            c.createStatement().execute("create table orders(id serial primary key, sku text not null)");
            c.createStatement().execute("insert into orders(sku) values ('SKU-1')");

            var rs = c.createStatement().executeQuery("select sku from orders");
            rs.next();
            assertEquals("SKU-1", rs.getString(1));
        }
    }
}

@Testcontainers starts and stops containers around the tests, and @Container marks the field. A static field means one container for all the tests in the class, started once. A non-static field starts a fresh container for every test method, which is clean and costs several seconds each time. Use static unless a test must start from an empty database, and then reset the data with a script instead of a new container. Pin the image tag to the version you run in production. postgres:latest gives you a different database on a different day and a flaky history.

Ports and URLs

The container's database listens on 5432 inside, and Testcontainers publishes it on a random free port on the host. Never hard-code 5432. Read the values from the container object, as above, or ask for the JDBC URL, which already contains the mapped port. Random ports are what let tests run in parallel on a developer machine and on a CI agent that has its own PostgreSQL installed. A test that connects to localhost:5432 works by accident on one machine and fails on the next.

MySQL, MariaDB and the rest

The pattern is the same for MySQLContainer, MariaDBContainer, MSSQLServerContainer, OracleContainer and others, each with its own module. A URL form needs no Java code at all and suits tools that only accept a connection string:

Text
jdbc:tc:postgresql:17:///testdb

The tc: prefix makes the JDBC driver start a container on the first connection. It is convenient for a quick start, and a Java field gives you more control over the lifecycle.

Initialising the schema

Create the schema the way production does. If you use Flyway or Liquibase, run the real migrations on the container, because that tests the migrations themselves: a script with a syntax error that H2 tolerates fails here.

java
@BeforeAll
static void migrate() {
    Flyway.configure()
          .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())
          .load()
          .migrate();
}

For a one-off script, withInitScript("schema.sql") loads a file from the classpath when the container starts. The migration tool is described in the Flyway documentation, and the idea of running migrations in a pipeline is in database migrations in CI.

Each test needs a known starting state. Run tests in a transaction that rolls back, or truncate the tables before each test. Do not rely on test order for data; if tests depend on one another, the ordering rules in JUnit test order explain why that is a trap.

Performance

Starting a PostgreSQL container takes a few seconds, and pulling the image the first time takes longer. Three habits keep a suite fast. Share one container across test classes with the singleton pattern or Spring's context caching, so the start happens once per run. Enable reuse for local development, with withReuse(true) on the container and testcontainers.reuse.enable=true in ~/.testcontainers.properties, so a container survives between runs; the details are in reusing containers. And keep slow database tests few and focused, leaving the rest of the logic to plain unit tests. Do not enable reuse on CI, where you want every run to start clean.

When the container does not start

Most failures are about Docker, not about your code. "Could not find a valid Docker environment" means the daemon is not reachable; the causes and fixes are in that error's guide. On a CI system without a Docker daemon, you need an alternative runtime or a remote one, covered in Testcontainers in CI without Docker. A timeout waiting for the database usually means a slow machine or a wrong image tag. Raise the startup timeout before assuming a bug.

Spring Boot

Boot connects the application to the container for you:

java
@SpringBootTest
@Testcontainers
class OrderServiceIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired OrderService service;
}

@ServiceConnection replaces the old @DynamicPropertySource boilerplate that copied the URL and credentials into Spring properties by hand. The mechanism is described in service connections. Spring then creates the DataSource against the container, and Flyway runs on startup as it does in production. For a first look at plain JDBC against a database, see connecting with JDBC.

Testing a migration against real data

A container makes one more kind of test cheap: running a migration against a database that already has rows. Load a small dump that resembles production, with awkward values such as nulls, very long text and duplicate keys, apply the new migration, and assert on the result. A migration that adds a not-null column with no default passes on an empty schema and fails on a populated table, and this is how you find out before the deployment does. Keep the dump small and anonymised; a few hundred rows chosen for their awkwardness beat a million copied from a live system. This is also the place to check that the migration is fast enough to run in a deployment window, though a container on a laptop is a rough guide and not a rehearsal.

When Testcontainers is the wrong choice

Pure unit tests of business logic should not touch a database at all. Environments that cannot run Docker, such as some locked-down build servers, need another approach, usually a shared test database that is reset between runs. A very large suite on slow hardware may prefer a handful of integration tests and many unit tests. The Testcontainers site documents every database module, including options such as wait strategies and custom images.

Also inHibernate
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.