Video in progress

Strong Middle 🧪 Testing

How do you speed up a suite of integration tests written with Testcontainers?

The main win is to start the container once per JVM instead of once per test class (the singleton pattern) and to keep a single Spring context. On top of that, lightweight images, local reuse, cleaning data with truncate, and splitting tests across parallel forks help.

📖 Answer

In many projects @Testcontainers + @Container static sits in every test class. A new PostgreSQL starts for each class, and because the container port changes, the Spring context can't use the cache either. 40 classes × (3 s container + 10 s context) is 9 minutes of pure waiting.

The singleton approach:

public abstract class AbstractIT {
    static final PostgreSQLContainer<?> POSTGRES =
        new PostgreSQLContainer<>("postgres:16-alpine");

    static { POSTGRES.start(); }   // once per JVM; Ryuk removes it at the end

    @DynamicPropertySource
    static void db(DynamicPropertyRegistry r) {
        r.add("spring.datasource.url", POSTGRES::getJdbcUrl);
        r.add("spring.datasource.username", POSTGRES::getUsername);
        r.add("spring.datasource.password", POSTGRES::getPassword);
    }
}

There's no @Container here, otherwise JUnit would stop it at the end of the class.

Other methods:

  • testcontainers.reuse.enable=true (in ~/.testcontainers.properties) and .withReuse(true): for local work the container doesn't die between test runs. Not meant for CI;
  • if you have many Flyway migrations, apply them once and then only TRUNCATE before each test;
  • for PostgreSQL in test mode, fsync=off (.withCommand("postgres", "-c", "fsync=off")) makes writes faster;
  • parallel forks with Surefire/Failsafe forkCount: each fork gets its own container, so count your CPU and memory.

Measure first: a Gradle build scan or the times in the Surefire report show which phase takes the most. Often the problem isn't the container but the context being restarted.