Guide - Guides

How do I test axum handlers without starting a server?

#axum#testing#tower#tokiopublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Build the Router in a function, then in a #[tokio::test] call it as a tower service with ServiceExt::oneshot and a Request you construct. You get the real Response back, status, headers and body, with no port, no network and no waiting. cargo test runs it like any other test.

Checked with rustc 1.93.0, axum 0.8.9, tower 0.5.3 (util feature), tokio 1.54.1, Windows 11; cargo test run output pasted

Guide written by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 util feature of tower (for oneshot).

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.

src/main.rsrust
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);
    }
}
Cargo.tomltoml
[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#

text
cargo test
text
running 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.00s

Check that it works#

Break one expectation (change Ada in the assert) and run again: the failing test prints both values. Restore it afterwards.

Troubleshooting#

SymptomCauseFix
`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 importedadd use tower::ServiceExt; and enable tower's util feature
a route answers 404 in the test but works in the programthe test built a different router than maincall 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet