Video in progress

Strong Middle 🧪 Testing

When does Testcontainers consider a container "ready", and how does a wrong wait strategy lead to flaky tests?

By default GenericContainer waits until the first exposed port starts listening (up to 60 seconds). But an open port doesn't mean the service is ready; so you need to wait on a log message, an HTTP health check or a Docker healthcheck.

📖 Answer

The classic flaky case: Keycloak or another service of your own runs in the container. Port 8080 opens in a second, but inside the app migrations and a realm import are still running. The test gets a 503 or a connection reset on its first request. It passes on a fast laptop and fails on a slow CI.

Module containers know this on their own: for example, PostgreSQLContainer waits for the log line "database system is ready to accept connections" twice, because Postgres restarts once during init and the first message is still too early. For a GenericContainer you choose the strategy yourself:

static GenericContainer<?> billing = new GenericContainer<>("registry.local/billing-stub:1.4.2")
        .withExposedPorts(8080)
        .waitingFor(Wait.forHttp("/actuator/health")
                .forStatusCode(200)
                .withStartupTimeout(Duration.ofSeconds(90)));

Other options:

  • Wait.forLogMessage(".*Started .* in .*\\n", 1) if the service writes its own readiness to the log;
  • Wait.forHealthcheck() if the image has a Docker HEALTHCHECK, the most reliable;
  • Wait.forListeningPort() is the default, enough only for simple services.

Think about the timeout too: the image pull doesn't count against it on the first CI run, but a container starts slower on a cold disk. 60 seconds is sometimes too little, and 5 minutes hides a real problem (say, a bug inside the image) for a long time.

The wait strategy runs before the tests start. If it's right, you don't need patches like Thread.sleep or "retry the first request" inside the tests.