Test-Containers in Golang (NATS)
Test-containers in Go is a Go package that makes it simple to create and clean up container-based dependencies for automated integration/smoke tests.
We use test-containers to run our dependent services like databases in a container hence we won’t need to mock them or use real external services. This makes our uint tests more efficient and more reliable.
The clean, easy-to-use API enables developers to programmatically define containers that should be run as part of a test and clean up those resources when the test is done.
Nats example
In the following example, we are going to create a Nats container and test it.
The testcontainers.ContainerRequest
describes how the Docker container will look.
Image
is the Docker image the container starts from.ExposedPorts
lists the ports to be exposed from the container.Cmd
is the commands that will be executed when container is set.WaitingFor
is a field you can use to validate when a container is ready. It is important to get this set because it helps to know when the container is ready to receive any traffic. In this case, we check for the logs we know come from Nats, telling us that it is ready to accept requests.
When you use ExposedPorts you have to imagine yourself using docker run -p <port>
. When you do so, dockerd maps the selected <port>
from inside the container to a random one available on your host.
testcontainers.GenericContainer
creates the container. In this example we are using Started: true
. It means that the container function will wait for the container to be up and running. If you set the Start value to false it won't start, leaving to you the decision about when to start it.
All the containers must be removed at some point, otherwise they will run until the host is overloaded. One of the ways we have to clean up is by deferring the terminated function: defer container.Terminate(ctx)
.
See the source code at my Github repository.
Thank you
Amirhossein Najafizade