Skip to content

Wait Strategies

Wait strategies are useful to detect if a container is ready for testing (i.e., if the application inside the container is in a usable state). They check different indicators of readiness of the container and complete as soon as they are fulfilled. Per default, Testcontainers will wait until the container is running. For the most images, that is not enough. You can chain different pre-configured wait strategies together or implement your own by implementing the IWaitUntil interface.

_ = Wait.ForUnixContainer()
  .UntilOperationIsSucceeded(() => true, 1)
  .AddCustomWaitStrategy(new MyCustomWaitStrategy());

In some cases, it might be necessary to configure the behavior of a wait strategy further, being able to cancel the readiness check. The API provides a callback that allows setting additional configurations such as Retries, Interval, and Timeout.

Cancel the readiness check after one minute
_ = Wait.ForUnixContainer()
  .UntilMessageIsLogged("Server started", o => o.WithTimeout(TimeSpan.FromMinutes(1)));

Besides configuring the wait strategy, cancelling a container start can always be done utilizing a CancellationToken.

Wait until an HTTP(S) endpoint is available

You can choose to wait for an HTTP(S) endpoint to return a particular HTTP response status code or to match a predicate. The default configuration tries to access the HTTP endpoint running inside the container. Chose ForPort(ushort) or ForPath(string) to adjust the endpoint or UsingTls() to switch to HTTPS. When using UsingTls() port 443 is used as a default. If your container exposes a different HTTPS port, make sure that the correct waiting port is configured accordingly.

Waiting for HTTP response status code 200 OK on port 80

_ = Wait.ForUnixContainer()
  .UntilHttpRequestIsSucceeded(request => request

Waiting for HTTP response status code 200 OK or 301 Moved Permanently

_ = Wait.ForUnixContainer()
  .UntilHttpRequestIsSucceeded(request => request

Waiting for the HTTP response status code to match a predicate

_ = Wait.ForUnixContainer()
  .UntilHttpRequestIsSucceeded(request => request
    .ForStatusCodeMatching(statusCode => statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices));

Wait until the container is healthy

If the Docker image supports Dockers's HEALTHCHECK feature, like the following configuration:

FROM alpine
HEALTHCHECK --interval=1s CMD test -e /healthcheck

You can leverage the container's health status as your wait strategy to report readiness of your application or service:

_ = new ContainerBuilder()