Video in progress

Middle 🧪 Testing

If a Testcontainers container runs on a random port, how do you pass its address into the Spring configuration?

In Spring Boot 3.1+, putting @ServiceConnection on the container field is enough: Boot picks up the connection details itself. For unsupported services or custom properties, use @DynamicPropertySource.

📖 Answer

Testcontainers picks a random host port every time, so you can't write localhost:5432 in application-test.yml.

@DynamicPropertySource is the universal way:

@Container
static GenericContainer<?> minio = new GenericContainer<>("minio/minio:RELEASE.2024-10-13T13-34-11Z")
        .withCommand("server /data")
        .withExposedPorts(9000);

@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
    registry.add("storage.endpoint",
        () -> "http://" + minio.getHost() + ":" + minio.getMappedPort(9000));
}

Using a Supplier matters: the value is computed while the context is starting, after the container has already started.

@ServiceConnection does everything automatically for well-known containers like PostgreSQL, MySQL, Kafka, Redis, MongoDB and RabbitMQ: spring.datasource.url, the user and the password.

So that several test classes can share the same container, I gather them in a separate configuration:

@TestConfiguration(proxyBeanMethods = false)
class Containers {
    @Bean @ServiceConnection
    PostgreSQLContainer<?> postgres() { return new PostgreSQLContainer<>("postgres:16-alpine"); }
}

Bonus: the same class can also be used to run the app locally through a TestApplication (SpringApplication.from(App::main).with(Containers.class)), so developers don't install a database by hand.