Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Testing and Deployment

Testing Handlers with oneshot

Test Axum routers without opening a socket. Build requests, call the Router with oneshot, read the response body, and structure fast unit and route tests, with runnable stand-ins.

An Axum Router is a Tower service: a value that turns a request into a response. That means you can test your whole routing table, extractors and middleware by handing the router a request and inspecting the response. No port, no network, no sleeping while a server starts. These tests run in milliseconds and fail with clear messages.

This lesson shows the real test code (read-only, because the real crates cannot run on this site) and builds a small stand-in router in plain Rust so you can run the same style of test here.

The real thing

Rust
use axum::{body::Body, http::{Request, StatusCode}, routing::get, Router};
use http_body_util::BodyExt;
use tower::ServiceExt; // for `oneshot`

fn app() -> Router {
    Router::new().route("/hello/{name}", get(|axum::extract::Path(name): axum::extract::Path<String>| async move {
        format!("hello, {name}")
    }))
}

#[tokio::test]
async fn hello_returns_greeting() {
    let response = app()
        .oneshot(Request::builder().uri("/hello/ada").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    assert_eq!(&bytes[..], b"hello, ada");
}

Four ideas carry the whole technique:

  1. Build the router in a function (fn app() -> Router). The real main calls it and so does every test. If you keep the router inline in main, you cannot test it.
  2. oneshot (from tower::ServiceExt) consumes the service, sends one request and returns the response future. Because it takes self, create a fresh router per test, or clone() it for several calls.
  3. Request::builder() from the http crate creates any request: method, URI, headers and body. Use Body::from(json_string) and a content-type header for JSON posts.
  4. BodyExt::collect() turns a streaming body into bytes you can compare. Add http-body-util as a dev dependency.

#[tokio::test] starts a Tokio runtime for the test function. Handlers are async, so every test that calls oneshot must be an async test.

Testing with state

Handlers that use State need the state to exist in the test. Build it with test-friendly parts: an in-memory fake instead of a real pool when you only need handler logic.

Rust
fn app_with(state: AppState) -> Router {
    Router::new()
        .route("/todos", get(list_todos).post(create_todo))
        .with_state(state)
}

#[tokio::test]
async fn create_then_list() {
    let state = AppState::in_memory();
    let app = app_with(state);

    let create = Request::builder()
        .method("POST")
        .uri("/todos")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"title":"write tests"}"#))
        .unwrap();

    let response = app.clone().oneshot(create).await.unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);

    let list = Request::get("/todos").body(Body::empty()).unwrap();
    let response = app.oneshot(list).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

Note app.clone() for the first call, because oneshot consumes the service. Cloning a Router is cheap: its routes are shared behind reference counts.

flowchart LR
    T["Test"] -->|"Request"| R["Router (Tower service)"]
    R --> M["Middleware layers"]
    M --> H["Handler + extractors"]
    H -->|"Response"| T
    T --> A["assert status, headers, body"]

The test plays the role of the HTTP server: everything from routing to the handler is real, only the network is gone.

A stand-in you can run

The stand-in below models a router as a table from (method, path) to a handler function, and oneshot as a function that runs one request. It is not Axum, but the test style is identical: build the app, send a request, assert on status and body.

Rust A tiny router and oneshot (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Table-driven route tests

Many route tests differ only in the request and the expected answer. Put the cases in a table and loop. A failure then names the exact case, which is much easier to read than one giant test.

Rust A table of cases with a mini test runner (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

What to test, and what not to

  • Status codes and bodies for success and for each error path. The error cases (400, 401, 403, 404, 422) are where bugs hide.
  • Extractors: send a malformed JSON body and confirm you get the status you expect, not a 500.
  • Middleware: check that a protected route answers 401 without a token and 200 with one.
  • Not the framework itself. Do not test that Axum can route /hello/{name}; test that your handler does the right thing with the name.

Keep logic you can test without HTTP in plain functions (a validate_title(&str) -> Result<..>) and unit test those directly. Use oneshot tests for the wiring around them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a testable Axum app build its router in a function such as fn app() -> Router?

    A shared constructor means the tests run against exactly the routes production serves.
  2. 2. Why do tests often call app.clone().oneshot(req)?

    oneshot takes self by value. Router clones are cheap because routes are shared.
  3. 3. What does BodyExt::collect() give you in a test?

    Response bodies are streams. collect() gathers them into bytes so assertions are simple.
  4. 4. Which test gives the most value for a protected route?

    Test your own behavior, especially the unauthorized and error paths.

Summary

  • A Router is a Tower service, so tests can call it with oneshot and no network.
  • Build the router in a function, and give it test-friendly state.
  • Build requests with Request::builder(), read bodies with BodyExt::collect().
  • Use #[tokio::test] for async tests, and clone the router for repeated calls.
  • Table-driven cases keep route tests short and their failures readable.
  • Test your handlers' behavior and error paths, not the framework.

Next: Integration Tests with a Test Database