What you will build#
Three tests for a router with a health check and a JSON endpoint, running with cargo test.
Before you start#
- An axum project (see the thread on a minimal server).
- The
utilfeature oftower(foroneshot).
Steps#
1. Put the router in a function#
main and the tests must build the same router, so give it a function. A Router is a tower service, so it can be called directly.
2. Write the tests#
oneshot consumes the service; it is cheap to build a router per test. The body is read with axum::body::to_bytes.
use axum::{extract::Path, http::StatusCode, routing::get, Json, Router};
use serde_json::{json, Value};
/// Build the router in one function so that main and the tests use the same one.
fn app() -> Router {
Router::new().route("/health", get(|| async { "ok" })).route("/users/{id}", get(user))
}
async fn user(Path(id): Path<u32>) -> Result<Json<Value>, StatusCode> {
if id == 7 { Ok(Json(json!({ "id": 7, "name": "Ada" }))) } else { Err(StatusCode::NOT_FOUND) }
}
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
axum::serve(listener, app()).await.unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::{to_bytes, Body}, http::Request};
use tower::ServiceExt; // for `oneshot`
#[tokio::test]
async fn health_is_ok() {
let res = app().oneshot(Request::get("/health").body(Body::empty()).unwrap()).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
assert_eq!(&body[..], b"ok");
}
#[tokio::test]
async fn user_is_json() {
let res = app().oneshot(Request::get("/users/7").body(Body::empty()).unwrap()).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
let json: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json, json!({ "id": 7, "name": "Ada" }));
}
#[tokio::test]
async fn unknown_user_is_404() {
let res = app().oneshot(Request::get("/users/8").body(Body::empty()).unwrap()).await.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
}[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde_json = "1"
tower = { version = "0.5.3", features = ["util"] }3. Run them#
cargo testrunning 3 tests
test tests::health_is_ok ... ok
test tests::unknown_user_is_404 ... ok
test tests::user_is_json ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sCheck that it works#
Break one expectation (change Ada in the assert) and run again: the failing test prints both values. Restore it afterwards.
Troubleshooting#
| Symptom | Cause | Fix |
|---|---|---|
`error[E0599]: no method named oneshot found for struct Router<S> (the compiler adds: "trait ServiceExt which provides oneshot` is implemented but not in scope") | the trait is not imported | add use tower::ServiceExt; and enable tower's util feature |
| a route answers 404 in the test but works in the program | the test built a different router than main | call the same app() function in both |
Going further#
- Test the database layer with an in-memory SQLite database (see the thread on in-memory databases in tests).
- Test the middleware by building a router with only the layer and one dummy route.
Related questions#
Do I still need tests against a real running server?#
A few, for things the in-process call skips (the real socket, TLS, a reverse proxy in front). The in-process tests cover routing, extraction, status codes and bodies.
Does this work with actix-web?#
actix-web has its own helpers; see the thread on testing actix-web handlers.
Sources#
- axum, testing example in the repository: https://github.com/tokio-rs/axum/tree/main/examples/testing (read 2026-12-05)
- The Rust Book, writing tests: https://doc.rust-lang.org/book/ch11-01-how-to-write-tests.html