Using Test Containers
You'll learn how to spin up real, isolated dependencies like databases and message queues in Docker containers for each test run.
The Problem with Test Dependencies
Integration tests need real infrastructure—databases, message brokers, caching layers. Previously you learned about setting up test databases manually or using mocked external APIs. But manual setup is tedious, and shared test databases can cause conflicts between tests or developers.
What Are Test Containers?
Test Containers leverage Docker containerization to automatically start fresh, isolated instances of dependencies right when your tests run. Think of it like ordering a brand-new, fully-stocked kitchen for every cooking class—nothing is pre-used, nothing is shared, and it's thrown away when you're done.
Instead of:
- Installing PostgreSQL on every developer's machine
- Maintaining shared test database servers
- Writing complex setup scripts
- Worrying about leftover test data
You get:
- A real PostgreSQL container that starts automatically
- Complete isolation per test suite
- Known, clean state every time
- Zero installation for teammates
How It Works
Test container libraries (available in most languages) detect Docker on your machine and programmatically start containers before tests run. You get a connection string to the real, running service. When tests finish, containers are destroyed automatically.
This bridges the gap between "mocked dependencies" (fast but unrealistic) and "real external infrastructure" (realistic but hard to manage). You get the realism of actual databases and services with the convenience of automated, reproducible test environments.
Key Takeaway: Test Containers use Docker to automatically provision real, isolated infrastructure for integration tests, giving you production-like behavior without manual setup or shared state problems.