The Culture of Code
  1. Posts/

Running Testcontainers On Dynamic Ports

Running integration tests locally with Docker on fixed ports is not always possible due to port conflicts. This is especially true when running tests in shared CI environment with shared workers.

Fortunately, testcontainers allow to start Docker containers listening on a random port.

Here is an example:

// create and start container val container = GenericContainer("softwaremill/elasticmq-native") .withExposedPorts(9324) .withReuse(true) container.start() // create sqsClient val sqsPort = container.getMappedPort(9324) val clientBuilder = SqsAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.EU_CENTRAL_1) .httpClient(NettyNioAsyncHttpClient.builder().build()) .endpointOverride(URI.create("http://127.0.0.1:$sqsPort")) val sqsClient = clientBuilder.build(); // get queue usr val queueUrl = getQueueUrl(sqsQueueName); /* do some tests here */ // close resources sqsClient.close() container.close()