Testcontainers for Go requires installing the testcontainers-go library and configuring Docker access before starting containers in your test setup. Add the dependency to your module, import the package, and use genericContainer.Run to spin up services like databases or message queues within your TestMain or individual test functions.
import (
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestIntegration(t *testing.T) {
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: "postgres:15",
ExposedPorts: []string{"5432/tcp"},
WaitingFor: wait.ForLog("database system is ready to accept connections"),
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Fatal(err)
}
defer container.Terminate(ctx)
// Use container to get host port and run DB tests
}