Skip to content

Testcontainers

Testcontainers is a library that helps you to run your tests against real dependencies.

In this guide, you will learn how to use Testcontainers with LocalStack.

Terminal window
dotnet add package Testcontainers.LocalStack --version 3.0.0
var localStackContainer = new LocalStackBuilder().Build();
await localStackContainer.StartAsync()
.ConfigureAwait(false);
var config = new AmazonS3Config();
config.ServiceURL = localStackContainer.GetConnectionString();
using var client = new AmazonS3Client(config);

Some services like RDS require additional setup so that the correct port is exposed and accessible for the tests. The reserved ports on LocalStack are between 4510-4559, depending on your use case you might need to expose several ports using witExposedPorts.

Check the pro-sample on how to use RDS with Testcontainers for Java.

The Testcontainer can be created like this:

/**
* Start LocalStackContainer with exposed Ports. Those ports are used by services like RDS, where several databases can be started, running on different ports.
* In this sample we only map 5 ports, however, depending on your use case you may need to map ports up to 4559
*/
@Rule
public LocalStackContainer localstack = new LocalStackContainer(DockerImageName("localstack/localstack:2.0.0"))
.withExposedPorts(4510, 4511, 4512, 4513, 4514) // the port can have any value between 4510-4559, but LS starts from 4510
.withEnv("LOCALSTACK_AUTH_TOKEN", auth_token); // add your Auth Token here

To find the exposed port which you can use to connect to the instance:

// identify the port localstack provides for the instance
int localstack_port = response.dbInstance().endpoint().port();
// get the port it was mapped to, e.g. the one we can reach from host/the test
int mapped_port = localstack.getMappedPort(localstack_port);