Using the Cosmos DB Emulator with Testcontainers
Customers often use the Azure Cosmos DB vNext Emulator with Testcontainers for integration testing in CI/CD pipelines. Here are three tips to help you get the most out of it.
1️⃣ Use the health probe ✅
The emulator exposes port 8080 for health checks. Testcontainers offers multiple wait strategies: configure the health port instead of sleeping for a fixed duration or matching hardcoded log messages. That’s a brittle anti-pattern! 🚫
2️⃣ Use port mappings, but carefully ⚠️
Testcontainers can assign random host ports to avoid conflicts. Use the mapped port to build the emulator’s endpoint URL. But here’s the tricky part: the emulator advertises its internal port during discovery, which can cause SDK connection failures.
With the testcontainers-go package, you can resolve this using a custom HTTP transport that rewrites requests to use the mapped port.
3️⃣ Emulator lifecycle management ♻️
Use Testcontainers to manage the emulator lifecycle (start/stop), ensuring clean test runs and no resource leaks.
For Go apps, you can include most of this in the TestMain function: For example, I use it to start the container, configure the client with the mapped port and custom transport, set up the database schema, seed test data, run all tests, and finally terminate the container for cleanup.
Learn more:
- GitHub repo - https://github.com/abhirockzz/cosmosdb-testcontainers-go
- Blog post - https://dev.to/abhirockzz/integration-testing-for-go-applications-using-testcontainers-and-containerized-databases-3bfp
- testcontainers (Go) - https://golang.testcontainers.org/
- vNext emulator docs - https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-linux