expression

Axum: test a route method contract

Tower oneshot drives a router in process, waiting for readiness and sending a single request. A route test can check allowed and rejected methods without binding a socket. Clone the router to make separate calls; this does not test the actual HTTP transport. In-memory standalone Cargo example. Expected stdout (not executed): GET: 200 POST: 405 Common mistake: Testing only a successful request and overlooking rejected methods.

Formal Syntax & Structure

rust syntaxrust
router.clone().oneshot(request).await

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::routing::get;    let app = Router::new().route("/health", get(|| async { "ok" }));    for (method, expected) in [("GET", StatusCode::OK), ("POST", StatusCode::METHOD_NOT_ALLOWED)] {        let res = app.clone().oneshot(Request::builder().method(method).uri("/health").body(Body::empty()).unwrap()).await.unwrap();        assert_eq!(res.status(), expected);        println!("{method}: {}", res.status().as_u16());    }}
Rust Reference