Mocking external HTTP services

Learn how to replace a real external API with a wiremock server in tests, how to stub its answers, and how to check what your code actually sent it

Real code calls real services: a weather API, a payment provider, a user directory. A test that calls the real service is slow, needs network access and a key, and fails when the service is down or changes its answers. A mock replaces the service with a small server the test controls. The test tells the mock what to answer, the code under test talks to the mock over real HTTP, and the test checks the result and what the mock received. This page builds that setup with wiremock version 0.6, the Rust mocking library.

Where This Fits

Every earlier page in this chapter tested code that only talked to itself: a router, a stream, a socket. This page is the first where the code under test reaches outwards, to a service the app does not own. The handler here fetches weather from an external API and returns it, and the test replaces that API with a mock, so the suite runs anywhere, without a key, without the network, and with the same answers every time. It is the last page of the chapter, and it closes the loop: the app is tested from its own routes down to the services behind them.

Think of a rehearsal with a stand-in. The lead actor is the handler, and the weather service is an actor who could not come to rehearsal. The mock is the stand-in, who knows only the lines the scene needs, and says them on cue. The rehearsal tests the lead, not the stand-in, and it works because the stand-in stands in the same place and says the lines at the same time.

The Smallest Working Version

The smallest mock test has three parts: a function that fetches weather from a base URL, a mock server that answers one path, and a test that wires them together. The fetch function takes the base URL as an argument, which is the design decision that makes the whole page possible. A function that hardcodes the real API address cannot be pointed at a mock, and a function that takes the address can be pointed anywhere.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.13", features = ["json"], default-features = false }
thiserror = "2.0"

[dev-dependencies]
wiremock = "0.6"
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"

reqwest is the HTTP client the fetch function uses, version 0.13. The json feature turns on JSON body support, and default-features = false leaves out the TLS backends, because the mock speaks plain HTTP on the local machine and no TLS is needed. wiremock is a dev-dependency, because only the tests use it. The app never needs a mock server.

src/weather.rs
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Weather {
    pub city: String,
    pub temperature_c: f64,
    pub condition: String,
}

#[derive(Debug, Error)]
pub enum FetchError {
    #[error("upstream request failed")]
    Request,
    #[error("upstream returned an error status")]
    BadStatus,
    #[error("upstream body was not valid weather JSON")]
    BadBody,
}

pub async fn fetch_weather(
    client: &reqwest::Client,
    base_url: &str,
    city: &str,
) -> Result<Weather, FetchError> {
    let url = format!("{base_url}/weather/{city}");
    let response = client.get(&url).send().await.map_err(|_| FetchError::Request)?;
    if !response.status().is_success() {
        return Err(FetchError::BadStatus);
    }
    response.json::<Weather>().await.map_err(|_| FetchError::BadBody)
}

The function builds the URL from the base and the city, sends a GET, and turns the response into a Weather struct. Three things can go wrong, and each has its own variant: the request itself can fail, the service can answer with an error status, and the body can fail to parse as weather JSON. The error type names each one, so the handler and the tests can tell them apart.

The test starts the mock, stubs one answer, and calls the function:

tests/weather_test.rs
use axum_project::weather::{Weather, fetch_weather};
use serde_json::json;
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{method, path},
};

#[tokio::test]
async fn fetch_weather_reads_the_mock_directly() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/tokyo"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "tokyo",
            "temperature_c": 22.0,
            "condition": "cloudy"
        })))
        .mount(&mock_server)
        .await;
    let weather = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "tokyo")
        .await
        .unwrap();
    assert_eq!(
        weather,
        Weather { city: "tokyo".to_string(), temperature_c: 22.0, condition: "cloudy".to_string() }
    );
}

Run it with:

cargo test --test weather_test

The test passes, and it proves the fetch function works against a real HTTP server, with real request and response handling, without touching the real weather service.

Working Setup:

If the fetch test passes, the mock is up, the stub matches the request, and the parsing works. A failure here is usually a mismatch between the stub and the request: the wrong path, the wrong method, or a missing mount. The sections below take each of those apart.

The Mock, Piece by Piece

let mock_server = MockServer::start().await;

MockServer::start launches a real HTTP server in the background, on a random free port, and returns a handle to it. The random port is the same idea as the WebSocket page's port 0: no hardcoded port, no collisions between parallel tests, and no leftover server from an earlier run blocking the next one. Each test starts its own mock server and throws it away at the end.

Mock::given(method("GET"))
    .and(path("/weather/tokyo"))
    .respond_with(ResponseTemplate::new(200).set_body_json(json!({
        "city": "tokyo",
        "temperature_c": 22.0,
        "condition": "cloudy"
    })))
    .mount(&mock_server)
    .await;

A Mock is one rule: when a request matches, answer this way. Mock::given starts the rule with the first matcher, and .and adds more. method("GET") matches only GET requests, and path("/weather/tokyo") matches only that exact path. respond_with sets the answer, and ResponseTemplate::new(200) builds a 200 response, with set_body_json serialising the JSON value into the body and setting the content type to application/json at the same time. mount registers the rule with the server, and it is the step beginners most often forget: a mock that is never mounted never answers anything, and the server answers 404 to every request.

let weather = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "tokyo").await.unwrap();

mock_server.uri() returns the base address of the mock, like http://127.0.0.1:45231, and the test passes it as the base URL. The fetch function builds the full URL from it, sends the request, and the mock answers with the stubbed JSON. The request travels over a real socket, through real HTTP parsing, which is the point: the test exercises the serialisation, the headers, and the status handling, not just the parsing of a string.

The Concept Behind It

Mocking and stubbing are often confused, and the difference is worth one paragraph. A stub is a fixed answer: when asked this, say that. A mock is a stub plus a memory: it also records what it was asked, so the test can check the request as well as the answer. wiremock does both. The Mock is the stub, and the received_requests list is the memory. The tests on this page use both halves, because a handler that asks the wrong question and gets a lucky answer is still broken.

The other idea is the seam. A seam is the place where the code can be pointed at something else. The base URL argument is the seam in fetch_weather, and the state field holding it is the seam in the handler. Without a seam, the code is welded to the real service, and no test can replace it. With a seam, the test points the code at the mock, and production points it at the real service, and the code itself never knows the difference. Every function that calls an external service needs a seam like this, and the base URL argument is the simplest form it takes.

The Handler Behind the Mock

The fetch function on its own is useful, but the app serves it through a handler, and the handler is what the user actually tests in a full suite. The handler takes the base URL and the client from state, calls the fetch function, and turns the result into a response. An upstream failure becomes a 502, Bad Gateway, which is the honest status for "the service behind me failed", and it is distinct from the app's own 500, which means "I failed":

src/weather.rs
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use serde_json::json;

#[derive(Debug, Clone)]
pub struct WeatherState {
    pub base_url: String,
    pub client: reqwest::Client,
}

async fn weather_handler(
    State(state): State<WeatherState>,
    Path(city): Path<String>,
) -> Response {
    match fetch_weather(&state.client, &state.base_url, &city).await {
        Ok(weather) => (StatusCode::OK, Json(weather)).into_response(),
        Err(_) => (
            StatusCode::BAD_GATEWAY,
            Json(json!({ "error": "upstream service failed" })),
        )
            .into_response(),
    }
}

pub fn weather_app(state: WeatherState) -> Router {
    Router::new()
        .route("/weather/{city}", get(weather_handler))
        .with_state(state)
}

The handler returns a plain Response, not the shared AppError, because 502 is not one of the shared error variants, and the upstream failure is this handler's own concern. The body is the same single-word JSON shape the rest of the app uses, so clients see a consistent error format whether the failure came from this app or from behind it.

The test for the handler builds the state with the mock's address and sends a request through the router in memory, while the handler reaches out to the mock over real HTTP:

tests/weather_test.rs
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::weather::{WeatherState, weather_app};
use http_body_util::BodyExt;
use serde_json::Value;
use tower::ServiceExt;

fn weather_state(base_url: String) -> WeatherState {
    WeatherState { base_url, client: reqwest::Client::new() }
}

#[tokio::test]
async fn mock_200_flows_through_the_handler() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let app = weather_app(weather_state(mock_server.uri()));
    let response = app
        .oneshot(Request::builder().uri("/weather/paris").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(body, json!({ "city": "paris", "temperature_c": 18.5, "condition": "sunny" }));
}

That test is the shape of a real integration test: the router runs in memory, the mock runs on a socket, and the handler bridges the two. The oneshot call exercises the handler, and the mock exercises the HTTP client. Neither side is faked.

Test sends GET /weather/paris to the router (in memory)
        |
        v
Handler calls fetch_weather with the mock base URL
        |
        v
reqwest sends GET /weather/paris to the mock (real HTTP)
        |
        v
Mock answers 200 with the stubbed JSON
        |
        v
Handler returns the weather as JSON with status 200

Stubbing the Failure Cases

A mock that only ever answers 200 tests only the happy path. The failures are where the handler earns its keep, and the mock can produce each one on demand. An upstream 500 becomes a 502 from the handler:

tests/weather_test.rs
#[tokio::test]
async fn upstream_500_becomes_502_from_the_handler() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&mock_server)
        .await;
    let app = weather_app(weather_state(mock_server.uri()));
    let response = app
        .oneshot(Request::builder().uri("/weather/paris").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(body, json!({ "error": "upstream service failed" }));
}

The stub is one line: ResponseTemplate::new(500) with no body. The fetch function sees a non-success status and returns BadStatus, the handler turns it into a 502 with the generic body, and the test asserts both. The same shape covers a slow service, with set_delay, and a broken body, with a stub that returns 200 and text that is not weather JSON, which the fetch function turns into BadBody and the handler turns into the same 502.

A request the mock has no rule for is answered with 404 by the mock itself. That is the mock's default, and it is a useful check in its own right:

tests/weather_test.rs
#[tokio::test]
async fn unmatched_mock_request_is_a_404_from_the_mock() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let result = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "london").await;
    assert!(result.is_err());
}

The stub covers Paris, the fetch asks for London, the mock answers 404, and the fetch function returns BadStatus. The test proves the mock does not answer everything with the stubbed weather, which would hide a handler that asks for the wrong city. A mock that answers every path with the same body is a stub that cannot catch a wrong URL, and this test is the check that it can.

Checking What the Mock Received

The stub half of the mock checks the answer. The memory half checks the question. After the fetch runs, the test asks the mock what it received:

tests/weather_test.rs
#[tokio::test]
async fn mock_server_records_the_request_it_received() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await.unwrap();
    let received = mock_server.received_requests().await.unwrap();
    assert_eq!(received.len(), 1);
    assert_eq!(received[0].method.as_str(), "GET");
    assert_eq!(received[0].url.path(), "/weather/paris");
}

received_requests returns every request the mock saw, in order, and the test asserts there was exactly one, that it was a GET, and that it hit the right path. The count matters as much as the path: a handler that calls the service twice, once to check and once to fetch, would pass a test that only checks the answer, and fail this one. The received list is the proof the handler asked once, asked the right thing, and asked it in the right way.

A mock can also require a header before it answers. The header matcher adds that condition to the rule, and a request without the header falls through to the mock's 404:

tests/weather_test.rs
use wiremock::matchers::header;

#[tokio::test]
async fn mock_can_require_an_api_key_header() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .and(header("x-api-key", "test-key-123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let client = reqwest::Client::new();
    let without_key = client
        .get(format!("{}/weather/paris", mock_server.uri()))
        .send()
        .await
        .unwrap();
    assert_eq!(without_key.status(), 404);
    let with_key = client
        .get(format!("{}/weather/paris", mock_server.uri()))
        .header("x-api-key", "test-key-123")
        .send()
        .await
        .unwrap();
    assert_eq!(with_key.status(), 200);
}

The first request carries no key, and the mock answers 404, because no rule matches it. The second carries the key, and the mock answers 200. The test proves the matcher works, and it is the pattern for testing that a client sends the credentials the real service requires. The key here is a throwaway test value, not a real credential, and it lives only in the test.

Scoped Mocks That Clean Up After Themselves

A mock mounted with mount stays active until the mock server shuts down. A mock mounted with mount_as_scoped stays active only while its guard is alive. Dropping the guard removes the rule, and later requests fall through to the 404 again:

tests/weather_test.rs
#[tokio::test]
async fn scoped_mock_disappears_when_its_guard_drops() {
    let mock_server = MockServer::start().await;
    {
        let _guard = Mock::given(method("GET"))
            .and(path("/weather/paris"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "city": "paris",
                "temperature_c": 18.5,
                "condition": "sunny"
            })))
            .mount_as_scoped(&mock_server)
            .await;
        let ok = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await;
        assert!(ok.is_ok());
    }
    let gone = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await;
    assert!(gone.is_err());
}

The guard is bound to _guard, and the block ends, dropping it. The fetch inside the block succeeds, and the fetch after the block fails, because the rule is gone. Scoped mocks fit a test that needs a rule for one part and a different answer later, like a first call that succeeds and a retry that must see the service fail. A fresh mock server per test is still the default, and a scoped mock is the tool for the rarer case where one test needs the mock to change its mind halfway through.

One Mock Server Per Test:

Each test starts its own MockServer, so its rules never collide with another test's rules, even when the tests run in parallel. Sharing one server across tests means sharing one rule set, and a rule added by one test can answer a request from another. The server is cheap to start, and the isolation is worth it.

Common Beginner Mistakes

Forgetting to mount the mock

// Wrong - the rule is built but never registered, so the mock answers 404
Mock::given(method("GET"))
    .and(path("/weather/paris"))
    .respond_with(ResponseTemplate::new(200));

Without .mount(&mock_server).await, the rule exists only in the test's memory, and the server knows nothing about it. Every request gets the mock's default 404, and the fetch fails with BadStatus. The failure looks like the handler or the client is broken, when the real mistake is the missing mount. If a mock answers 404 to a request that has a rule, check the mount first.

Hardcoding the real service URL in the fetch function

// Wrong - no seam, so no test can point this at a mock
const BASE_URL: &str = "https://api.weather.example.com";

pub async fn fetch_weather(client: &reqwest::Client, city: &str) -> Result<Weather, FetchError> {
    let url = format!("{BASE_URL}/weather/{city}");
    // ...
}

A hardcoded address welds the function to the real service. The test cannot change it, short of editing the code, and the suite needs the network and a key. Pass the base URL as an argument, as the function on this page does, and the same code serves production and tests with one value changed.

Matching too little, or too much

A rule with only method("GET") and no path answers every GET with the same body, so a handler that asks for the wrong city still gets weather, and the test passes while the URL is wrong. A rule that matches the path, the method, three headers, and the exact body is brittle, and it breaks whenever the client sends an extra header it did not send before. Match the method and the path, add a header matcher only when the header is part of the contract, and leave the rest alone.

Asserting only the answer, never the request

A test that checks the handler's response and never looks at received_requests cannot catch a handler that asks twice, asks the wrong path, or sends the wrong headers. The answer can be right for the wrong reasons. Check the received requests when the request itself is part of the contract, which is most of the time for a client that talks to a paid or rate-limited service.

Never Point a Test at the Real Service:

A test that calls the real weather API needs the network, a key, and the service to be up, and it fails when any of those change. It can also spend real money, burn a rate limit, and write real data into a real account. The mock exists so the suite runs anywhere, offline, with the same answers every time. If a test needs the real service to prove something, that proof belongs in a manual check, not in the suite.

Final Complete Example

The whole test file, with the state helper and all seven tests, against the handler and fetch function from this page:

tests/weather_test.rs
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::weather::{Weather, WeatherState, fetch_weather, weather_app};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{header, method, path},
};

fn weather_state(base_url: String) -> WeatherState {
    WeatherState { base_url, client: reqwest::Client::new() }
}

#[tokio::test]
async fn fetch_weather_reads_the_mock_directly() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/tokyo"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "tokyo",
            "temperature_c": 22.0,
            "condition": "cloudy"
        })))
        .mount(&mock_server)
        .await;
    let weather = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "tokyo")
        .await
        .unwrap();
    assert_eq!(
        weather,
        Weather { city: "tokyo".to_string(), temperature_c: 22.0, condition: "cloudy".to_string() }
    );
}

#[tokio::test]
async fn mock_200_flows_through_the_handler() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let app = weather_app(weather_state(mock_server.uri()));
    let response = app
        .oneshot(Request::builder().uri("/weather/paris").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(body, json!({ "city": "paris", "temperature_c": 18.5, "condition": "sunny" }));
}

#[tokio::test]
async fn upstream_500_becomes_502_from_the_handler() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&mock_server)
        .await;
    let app = weather_app(weather_state(mock_server.uri()));
    let response = app
        .oneshot(Request::builder().uri("/weather/paris").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(body, json!({ "error": "upstream service failed" }));
}

#[tokio::test]
async fn unmatched_mock_request_is_a_404_from_the_mock() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let result = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "london").await;
    assert!(result.is_err());
}

#[tokio::test]
async fn mock_server_records_the_request_it_received() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await.unwrap();
    let received = mock_server.received_requests().await.unwrap();
    assert_eq!(received.len(), 1);
    assert_eq!(received[0].method.as_str(), "GET");
    assert_eq!(received[0].url.path(), "/weather/paris");
}

#[tokio::test]
async fn mock_can_require_an_api_key_header() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/weather/paris"))
        .and(header("x-api-key", "test-key-123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "city": "paris",
            "temperature_c": 18.5,
            "condition": "sunny"
        })))
        .mount(&mock_server)
        .await;
    let client = reqwest::Client::new();
    let without_key = client
        .get(format!("{}/weather/paris", mock_server.uri()))
        .send()
        .await
        .unwrap();
    assert_eq!(without_key.status(), 404);
    let with_key = client
        .get(format!("{}/weather/paris", mock_server.uri()))
        .header("x-api-key", "test-key-123")
        .send()
        .await
        .unwrap();
    assert_eq!(with_key.status(), 200);
}

#[tokio::test]
async fn scoped_mock_disappears_when_its_guard_drops() {
    let mock_server = MockServer::start().await;
    {
        let _guard = Mock::given(method("GET"))
            .and(path("/weather/paris"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "city": "paris",
                "temperature_c": 18.5,
                "condition": "sunny"
            })))
            .mount_as_scoped(&mock_server)
            .await;
        let ok = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await;
        assert!(ok.is_ok());
    }
    let gone = fetch_weather(&reqwest::Client::new(), &mock_server.uri(), "paris").await;
    assert!(gone.is_err());
}

Run the tests with:

cargo test --test weather_test

All seven tests pass. The mock answers the happy path and the failure path, the handler turns upstream failures into 502s, the unmatched request gets the mock's 404, the received-requests check proves the handler asked once and asked the right path, the header matcher proves the key is required, and the scoped mock proves a rule can be removed mid-test.

Summary

Mocking is the test's way of saying the code under test is the handler and the client, not the service behind them. The seam is the base URL, the stub is the rule, and the memory is the received-requests list, and the three together let a test check the question, the answer, and the translation between them, without the network, without a key, and without waiting on anyone else's server. A suite that mocks its dependencies runs anywhere, and it runs the same way every time, which is the property the whole chapter has been building towards.

The decision to carry forward is to give every external call a seam, and to test through it with a fresh mock per test. The chapter's arc ends here: unit tests for pure functions, integration tests through the router, fixtures for data, tokens for identity, real sockets for streaming transports, and mocks for the world outside. A test suite that covers all six can change the code inside with confidence, because every layer has a test that would catch the change breaking it.