Integration Testing with testcontainers-rs in Rust
Integration tests that mock databases lie. Your code might pass with a mock PostgreSQL but break with real transaction semantics, constraint enforcement, or specific data types. testcontainers-rs solves this by spinning up real Docker containers for your tests — and tearing them down when done.
This guide covers using testcontainers-rs in Rust projects for real integration testing against PostgreSQL, Redis, and custom containers.
The Problem with Database Mocks
Mocking a database for tests creates a parallel implementation of database semantics — one that's inevitably incomplete. Common failures:
- SQL syntax differences — mock accepts invalid SQL that real Postgres rejects
- Constraint violations — unique, foreign key, and check constraints silently ignored
- Transaction isolation — mock doesn't model MVCC or deadlock detection
- Data type edge cases — JSON, arrays, and custom types behave differently
The alternative is running real databases in tests. testcontainers-rs makes this practical by managing container lifecycle automatically.
Setup
Add dependencies to Cargo.toml:
[dev-dependencies]
testcontainers = "0.22"
testcontainers-modules = { version = "0.11", features = ["postgres", "redis"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }You'll need Docker running locally (or in CI).
PostgreSQL Tests
Here's a complete example testing database operations:
use testcontainers::{clients::Cli, Container};
use testcontainers_modules::postgres::Postgres;
#[tokio::test]
async fn test_user_creation() {
let docker = Cli::default();
let container = docker.run(Postgres::default());
let port = container.get_host_port_ipv4(5432);
let connection_string = format!(
"postgres://postgres:postgres@127.0.0.1:{}/postgres",
port
);
// Run your migration
sqlx::migrate!("./migrations")
.run(&pool)
.await
.unwrap();
let pool = sqlx::PgPool::connect(&connection_string)
.await
.unwrap();
// Now test with real Postgres
let user_id = create_user(&pool, "alice@example.com").await.unwrap();
let user = get_user(&pool, user_id).await.unwrap();
assert_eq!(user.email, "alice@example.com");
// Container automatically removed when `container` drops
}The container lives as long as the container variable is in scope. When it drops, Docker removes it. No manual cleanup needed.
Configuring the Postgres Container
Customize the Postgres image and credentials:
use testcontainers_modules::postgres::Postgres;
let pg = Postgres::default()
.with_db_name("myapp_test")
.with_user("testuser")
.with_password("testpass");
let container = docker.run(pg);
let connection_string = format!(
"postgres://testuser:testpass@127.0.0.1:{}/myapp_test",
container.get_host_port_ipv4(5432)
);Use a specific Postgres version to match production:
use testcontainers::{core::WaitFor, GenericImage};
let pg = GenericImage::new("postgres", "15.4")
.with_env_var("POSTGRES_DB", "testdb")
.with_env_var("POSTGRES_USER", "testuser")
.with_env_var("POSTGRES_PASSWORD", "secret")
.with_wait_for(WaitFor::message_on_stderr(
"database system is ready to accept connections"
));Matching the production Postgres version prevents subtle incompatibilities from surfacing in production.
Redis Tests
use testcontainers_modules::redis::Redis;
#[tokio::test]
async fn test_cache_operations() {
let docker = Cli::default();
let container = docker.run(Redis::default());
let port = container.get_host_port_ipv4(6379);
let client = redis::Client::open(format!("redis://127.0.0.1:{}", port))
.unwrap();
let mut conn = client.get_async_connection().await.unwrap();
// Set a key with TTL
redis::cmd("SET")
.arg("session:abc123")
.arg("user:42")
.arg("EX")
.arg(300)
.query_async::<_, ()>(&mut conn)
.await
.unwrap();
// Verify TTL was set
let ttl: i64 = redis::cmd("TTL")
.arg("session:abc123")
.query_async(&mut conn)
.await
.unwrap();
assert!(ttl > 0 && ttl <= 300);
}Custom Container Images
For services without a pre-built module, use GenericImage:
use testcontainers::{core::WaitFor, GenericImage};
#[tokio::test]
async fn test_against_custom_service() {
let docker = Cli::default();
let container = docker.run(
GenericImage::new("mycompany/myservice", "latest")
.with_env_var("SERVICE_MODE", "test")
.with_env_var("LOG_LEVEL", "debug")
.with_exposed_port(8080)
.with_wait_for(WaitFor::http(
WaitFor::message_on_stdout("Server started")
))
);
let port = container.get_host_port_ipv4(8080);
let base_url = format!("http://127.0.0.1:{}", port);
// Test against the real service
let response = reqwest::get(&format!("{}/health", base_url))
.await
.unwrap();
assert_eq!(response.status(), 200);
}Sharing Containers Across Tests
Starting a container for every test is slow. For a test module that all needs the same database, share a container using OnceLock or Tokio's OnceCell:
use std::sync::OnceLock;
use testcontainers::{clients::Cli, Container};
use testcontainers_modules::postgres::Postgres;
static DOCKER: OnceLock<Cli> = OnceLock::new();
fn get_docker() -> &'static Cli {
DOCKER.get_or_init(Cli::default)
}
// Shared connection pool for all tests in this module
async fn get_test_pool() -> &'static sqlx::PgPool {
static POOL: tokio::sync::OnceCell<sqlx::PgPool> = tokio::sync::OnceCell::const_new();
POOL.get_or_init(|| async {
let docker = get_docker();
// Note: container leaked intentionally — lives for process lifetime
let container = Box::leak(Box::new(docker.run(Postgres::default())));
let port = container.get_host_port_ipv4(5432);
let pool = sqlx::PgPool::connect(&format!(
"postgres://postgres:postgres@127.0.0.1:{}/postgres", port
))
.await
.unwrap();
sqlx::migrate!("./migrations").run(&pool).await.unwrap();
pool
})
.await
}
#[tokio::test]
async fn test_create_user() {
let pool = get_test_pool().await;
// use shared pool
}
#[tokio::test]
async fn test_list_users() {
let pool = get_test_pool().await;
// use same container/pool
}Warning: shared containers mean tests can interfere. Use test-specific schemas or tables, or truncate tables in a test setup step:
async fn reset_db(pool: &sqlx::PgPool) {
sqlx::query("TRUNCATE TABLE users, orders CASCADE")
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn test_create_user() {
let pool = get_test_pool().await;
reset_db(pool).await;
// test with clean state
}Using Schemas for Isolation
A cleaner isolation approach: give each test its own schema:
async fn create_test_schema(pool: &sqlx::PgPool) -> String {
let schema = format!("test_{}", uuid::Uuid::new_v4().simple());
sqlx::query(&format!("CREATE SCHEMA {}", schema))
.execute(pool)
.await
.unwrap();
sqlx::query(&format!("SET search_path TO {}", schema))
.execute(pool)
.await
.unwrap();
// Run migrations in this schema
sqlx::migrate!("./migrations")
.run(pool)
.await
.unwrap();
schema
}Each test gets a fresh schema with its own tables. Tests run in parallel without interference. Drop schemas after tests complete.
Docker Availability in CI
testcontainers requires Docker. Most CI systems support it:
GitHub Actions
jobs:
test:
runs-on: ubuntu-latest # Docker available by default
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo testGitHub Actions Ubuntu runners include Docker. No additional setup needed.
GitLab CI
test:
image: rust:latest
services:
- docker:dind
variables:
DOCKER_HOST: tcp://docker:2376
script:
- cargo testCircleCI
Use a machine executor:
jobs:
test:
machine:
image: ubuntu-2204:current
steps:
- checkout
- run: cargo testWaiting for Readiness
Containers start fast, but the service inside takes time to be ready. testcontainers provides several wait strategies:
use testcontainers::core::WaitFor;
// Wait for a specific message in stdout/stderr
WaitFor::message_on_stdout("ready to accept connections")
WaitFor::message_on_stderr("started")
// Wait for an HTTP endpoint to return 2xx
WaitFor::http(
testcontainers::core::HttpWaitStrategy::new("/health")
.with_expected_status_code(200u16)
)
// Wait for a port to be open
WaitFor::tcp_port_is_open(5432)
// Fixed duration (avoid if possible — flaky in slow CI)
WaitFor::seconds(2)Prefer specific signals (log messages, HTTP health checks) over fixed durations — fixed waits are flaky in slow CI environments.
Cleaning Up
When the Container variable drops, testcontainers removes the Docker container. But if your test panics, cleanup still happens via Drop:
#[tokio::test]
async fn test_with_guaranteed_cleanup() {
let docker = Cli::default();
let container = docker.run(Postgres::default());
// Even if this panics, `container` drops and Docker cleans up
let result = std::panic::catch_unwind(|| {
// test code
});
// container drops here anyway
result.unwrap(); // re-panic if needed
}For longer-lived containers (leaked with Box::leak), use Docker's --rm flag in your CI pipeline to remove orphaned containers:
docker rm -f $(docker ps -aq) 2>/dev/null || truePerformance Considerations
Container startup takes 1-5 seconds depending on image size and your machine. For a large test suite:
- Share containers across tests in the same module (as shown above)
- Pull images in CI before running tests to avoid cold-start delays
- Use lightweight images —
postgres:15-alpinestarts faster thanpostgres:15 - Run container tests as a separate cargo test invocation:
cargo test --test integration
# CI: pull images first, then test
- name: Pull test images
run: |
docker pull postgres:15-alpine
docker pull redis:7-alpine
- name: Run tests
run: cargo testSummary
testcontainers-rs bridges the gap between fast unit tests and production reality:
- Real databases catch SQL syntax errors, constraint violations, and transaction edge cases that mocks miss
- Automatic cleanup via Drop means no test pollution between runs
- Shared containers amortize startup cost across test suites
- Schema isolation provides clean state per test without restart overhead
- CI support is straightforward on most platforms since Docker is available
For code that talks to databases or external services, a real container test will catch bugs that no amount of mocking can.