Running Testcontainers On Dynamic Ports
Running integration tests locally with Docker can be challenging when fixed ports are unavailable due to conflicts. This issue is compounded in shared CI environments where multiple workers are in use. However, using testcontainers can help overcome these obstacles by enabling the startup of Docker containers that listen on random ports.
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()