Lesson 11 of 14 · 20m
Testing Rust Services: Seams by Layer
sqlx::test per-test databases, wiremock real HTTP fakes over mocked clients, and cargo nextest's process-per-test answer to the flake class.
The standard answer to "how do we test this service" is a shared Postgres instance, a .env.test, and tests that pass locally and flake in CI. The suite isn't slow because Rust is slow — it's slow because every test chose the same heavyweight seam: the real database. Testing a Rust service well means matching the seam to the layer: pure functions get plain tests, trait boundaries get fakes, SQL gets a real database you control per-test, and external HTTP gets a fake server, not a mocked function.
The layer-to-seam map
pure domain logic → #[test], proptest — no I/O at all
trait seam → in-memory fake impl (MemoryStore from the traits lesson)
real SQL → fresh database per test (sqlx::test / testcontainers)
external HTTP → wiremock / httpmock — a real HTTP server on localhost
runner → cargo nextest — a process per test, not a threadThe wrong mental model is "mock everything" or its opposite "tests must be real." Mock the boundary you don't control — a billing API, a third-party webhook — and be real on the boundaries where your bugs live: your own SQL, your serialization, your lock ordering.
sqlx::test and testcontainers: real databases, per-test
sqlx ships a test attribute that creates a fresh database per test and drops it after:
#[sqlx::test(migrations = "./migrations")]
async fn insert_then_get_roundtrips(pool: PgPool) {
let repo = PgUserStore::new(pool);
repo.insert(&user("alice")).await.unwrap();
assert!(repo.get(user("alice").id).await.unwrap().is_some());
}Every test gets its own migrated database on a Postgres you point at (DATABASE_URL) — no shared state, no ordering games. When the dependency isn't just Postgres — Redis, an S3-compatible store, another service — testcontainers (testcontainers-rs) boots the real thing in a Docker container per test. Heavier per test, realer than any fake, and the same pattern CI runs.
wiremock: fake the server, not the client
For an outbound HTTP dependency, don't mock your reqwest wrapper — stand up a real HTTP server that answers on localhost:
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::{method, path};
#[tokio::test]
async fn billing_timeout_maps_to_502() {
let server = MockServer::start().await;
Mock::given(method("GET")).and(path("/v1/accounts"))
.respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
.mount(&server).await;
let client = BillingClient::new(server.uri()); // real reqwest, real URL
let err = client.get_account(1).await.unwrap_err();
assert!(matches!(err, BillingError::UpstreamTimeout));
}That test exercises the real HTTP client, the real TLS-free socket path, and — critically — the timeout you set in the earlier lesson. A mocked BillingApi trait can return Err(Timeout) on demand, but it can't tell you your reqwest builder forgot to set one. httpmock does the same job with a slightly different API; either beats a function-level mock for the thing you're actually unsure of: the wire.
nextest: the runner that kills the flake class
cargo test runs all tests as threads in one process. That means tests share the process environment, the working directory, and every global — std::env::set_var in test A leaks into test B, and serial attributes proliferate to paper over it. cargo nextest run (Meta's runner) gives every test its own process: no env races, no set_current_dir cross-talk, plus retries and a flaky-test report. serial_test is the band-aid; nextest removes the reason you needed it.
Snapshots belong in the same category: insta records a complex output (a rendered config, an error report) to a .snap file and diffs on the next run — the test you write when "assert equals 400 lines" is how the suite would otherwise look.
The bug that ships
The testing bug that ships is the suite that only ever runs against a TestUserStore fake — so the day PgUserStore's SQL has a transaction bug, nothing catches it until production. Fakes verify your logic. The real database verifies your SQL. You need both, and the seam decision is which layer each test lives at — not whether to test.
Try this
Take one handler test that currently hits a shared DATABASE_URL. Convert it to #[sqlx::test] with its own database. Then take the test that calls the billing API and move it to wiremock — feel the difference between "asserts the fake returned what I told it" and "asserts my client handled a real 30-second delay."
Field notes
tokio::testalready runs each test on its own runtime — you don't share the scheduler between tests.insta'scargo insta reviewworkflow is how snapshot diffs get approved; don't commit.snap.newfiles blind.- Testcontainers adds Docker as a dev-machine dependency — if your CI doesn't have it,
sqlx::testagainst a service container is the lighter path.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.
What Rust 1.79 Shipped
The Rust Development Team has unveiled Rust 1.79, marking another step forward in the evolution of the memory-safe programming language. This latest update, announced last week on June 13, brings stability to both inline const expressions and the associated item bounds syntax, providing…
Source-Based Coverage Arrived in Rust 1.60
Rust 1.60, introduced just this April 7, 2022, stabilizes support for LLVM-based coverage instrumentation in rustc. This provides for source-based code coverage. Developers can try this out by rebuilding their code with -Cinstrument-coverage. Afterward, running the resulting binary will produce…
What is Rust? The Language That Makes Systems Programming Safe
Rust eliminates entire categories of bugs — null pointer dereferences, buffer overflows, data races, use-after-free — at compile time with no runtime overhead. Microsoft, Google, Amazon, and the Linux kernel all use it for systems code.