tower ServiceExt
Learn what the tower ServiceExt trait adds to every service and how its oneshot ready and adapter methods let tests call a Router without a network socket
tower::ServiceExt is a trait that adds convenience methods to every Tower service, including an Axum Router. A trait is a named set of behaviour a type can promise to provide, and an extension trait is a trait that adds new methods to types that already exist, without changing those types. ServiceExt adds methods like oneshot, which sends one request and returns the response, ready, which waits until the service can accept a request, and map_response, which changes every response on the way out. Its one job is to make calling a service directly easy enough that tests can do it in a few lines.
Where This Fits
The unit test pages before this one tested plain functions, which need no server and no HTTP. A Router is different. It only answers HTTP requests, so testing it means sending a request to it somehow. Starting a real server on a port for every test is slow and fragile, and this trait is the alternative. It lets a test hand a request to the Router in memory, with no socket and no port, and read the response back.
Think of a restaurant kitchen with a service hatch. Customers normally order through the dining room, which is the network. The hatch lets the chef pass a plate straight to a waiter without the dining room at all. The food is the same, the kitchen is the same, and only the delivery path changes. ServiceExt is that hatch for a Router.
The Smallest Working Version
The smallest use of the trait is a single test that sends one request to the home route and checks the status. The project is the same book app the error pages built, with the app function in src/lib.rs and the AppError type in src/errors.rs. The only new piece is the test file.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn oneshot_sends_one_request_and_returns_the_response() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
The Cargo.toml file needs tower as a dev-dependency, with the util feature turned on. A dev-dependency is a crate used only by tests, never by the shipped program, and a feature is an optional part of a crate that stays off until a project asks for it. ServiceExt lives behind the util feature, so without it the trait does not exist and the import fails.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5.3", features = ["util"] }
Run the test with cargo test, and it passes:
test oneshot_sends_one_request_and_returns_the_response ... ok
The test builds the Router with app(), builds a request with Request::builder(), sends it through oneshot, awaits the result, unwraps it, and checks the status is 200. No server started, no port was bound, and no network packet was sent. The whole round trip happened inside the test process.
Working Setup:
If cargo test prints ok for this test, the tower dev-dependency is declared with the util feature, the trait is imported, and the Router answers a request in memory.
Understanding the Trait Definition
The trait is defined in the tower crate, in the tower::util module, and re-exported at the top of the crate as tower::ServiceExt. Its definition starts with a bound, a condition a type must meet before the trait applies to it.
pub trait ServiceExt<Request>: Service<Request> {
Service is the core Tower trait, and it describes anything that can take a request and return a response. Its two methods are poll_ready, which asks whether the service can accept a request right now, and call, which hands it a request. ServiceExt<Request>: Service<Request> means the extension trait only applies to types that already implement Service for that request type. A Router implements Service for HTTP requests, so the extension methods appear on it automatically. This is called a blanket implementation, one implementation that covers every type meeting the condition, so there is nothing to implement by hand. Importing the trait is what switches the methods on.
The methods themselves are provided methods, which means the trait supplies a default body for each one and no type has to write its own. That is why the trait works on Router with no extra code. The methods that matter most for tests are the first three in the definition, and the rest are adapters that wrap a service and change what it does.
oneshot
fn oneshot(self, req: Request) -> Oneshot<Self, Request>
oneshot takes the service by value, which means it consumes it, and takes one request. It returns a future, an async value that produces a result when awaited. The future waits until the service is ready, calls it once with the request, and resolves to Result<Response, Error>. For a Router, the error type is std::convert::Infallible, a type with no possible values, which means the result can never be an Err. That is why the test can call .unwrap() on it without worrying. The method gets its own page, because it carries the whole testing pattern, and this page treats it as the headline method of the trait.
ready
fn ready(&mut self) -> Ready<'_, Self, Request>
ready borrows the service mutably and returns a future that resolves to a mutable reference to the service once it is ready to accept a request. It does not send a request itself. It answers the question "can I call you now" and hands back the service so the caller can use the plain call method from the Service trait. It is the manual form of what oneshot does automatically, and it is useful when one service must handle several requests in a row without being consumed.
ready_oneshot
fn ready_oneshot(self) -> ReadyOneshot<Self, Request>
ready_oneshot is the consuming form of ready. It takes the service by value and returns a future that resolves to the service itself once it is ready. It is the middle step between doing nothing and sending a request, and it appears when a test needs the ready service back rather than a response.
call_all
fn call_all<S>(self, reqs: S) -> CallAll<Self, S>
call_all takes a stream of requests and returns a stream of responses. A stream is an async sequence of values, like an iterator that produces items over time. One Router fed a stream of ten requests produces a stream of ten responses, in order. Tests rarely need it, because tests usually send requests one at a time and assert on each, but it is the right tool when a whole batch of requests must run through the same service.
The adapter methods
The remaining methods wrap the service in a new service that changes requests, responses, or errors as they pass through. map_request changes each request before the service sees it. map_response changes each response after the service produces it. map_err changes the error, and map_result changes both the response and the error at once. and_then and then run an async function after the service responds, map_future changes the future the service returns, and boxed and boxed_clone turn the service into a trait object, a value whose exact type is hidden behind a pointer. The filter and filter_async methods need the separate filter feature and reject requests that fail a check before they reach the service. Of these, map_response is the one tests reach for most, because it can stamp a header onto every response or record what the service returned.
The Concept Behind an Extension Trait
Rust does not let one crate add methods to a type from another crate directly. That rule keeps method names from colliding across crates, but it makes a helper like oneshot impossible to write as a plain method on Router, because Router belongs to Axum and oneshot belongs to Tower. The extension trait is the sanctioned way around the rule. Tower defines a trait with the new methods, implements it for every type that already implements Service, and the user brings the methods into scope with one use line. The methods feel like they belong to the Router, and no crate had to change its own types to make that true.
The same pattern appears all over Rust. Iterator gains collect from a trait, Future gains await support from the language, and a Router gains oneshot from ServiceExt. The import line is the switch. Without use tower::ServiceExt;, the compiler reports that no method named oneshot exists, even though the Router is the same value. The method was never missing from the type. It was missing from scope.
The Import Is the Switch:
If the compiler says oneshot does not exist on a Router, the first thing to check is the use tower::ServiceExt; line at the top of the test file. The trait must be in scope for its methods to be callable, and the error message does not say that plainly.
Why Tests Use ServiceExt Instead of a Real Server
A test that starts a real server must pick a port, wait for the listener to bind, send a request over the network, and shut the server down again. Ports collide when tests run in parallel, startup adds delay to every test, and a test failure can leave a server running. A test that uses ServiceExt skips all of that. The Router is an ordinary value in the test process, the request is an ordinary value too, and the response comes back from the same call. Tests run in parallel without port conflicts, they run fast because there is no network, and a failing test leaves nothing behind.
There is a second reason, and it matters more. A test through ServiceExt exercises exactly the code the server runs. The same app() function builds the Router, the same routes match, the same handlers run, and the same error conversion builds the response. The only part missing is the network layer, which belongs to Tokio and Hyper, not to the app. If a test passes through oneshot and the server later fails on the same request, the failure is in the network setup, not in the app logic, and that split makes debugging far easier.
A Richer Complete Example
The smallest version sent one request. A realistic test file sends several, and it uses more than one method from the trait. This file uses oneshot for the simple cases, ready plus call for a service that must stay alive across requests, and map_response to stamp a header onto a response.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::{Service, ServiceExt};
#[tokio::test]
async fn oneshot_sends_one_request_and_returns_the_response() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn ready_then_call_does_what_oneshot_does_in_two_steps() {
let mut router = app();
let router = tower::ServiceExt::<Request<Body>>::ready(&mut router)
.await
.unwrap();
let request = Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap();
let response = router.call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn map_response_can_add_a_header_to_every_response() {
let service = tower::ServiceExt::<Request<Body>>::map_response(app(), |mut response: axum::response::Response| {
response
.headers_mut()
.insert("x-tested-by", "service-ext".parse().unwrap());
response
});
let response = service
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers().get("x-tested-by").unwrap(),
"service-ext"
);
}
#[tokio::test]
async fn oneshot_consumes_the_router_so_each_request_needs_its_own() {
let first = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(first.status(), StatusCode::OK);
let second = app()
.oneshot(
Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
#[tokio::test]
async fn a_cloned_router_works_for_a_second_oneshot() {
let router = app();
let first = router
.clone()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(first.status(), StatusCode::OK);
let second = router
.oneshot(
Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
Run it with cargo test, and all five tests pass:
test a_cloned_router_works_for_a_second_oneshot ... ok
test map_response_can_add_a_header_to_every_response ... ok
test oneshot_consumes_the_router_so_each_request_needs_its_own ... ok
test oneshot_sends_one_request_and_returns_the_response ... ok
test ready_then_call_does_what_oneshot_does_in_two_steps ... ok
The ready test shows the two-step form. ready borrows the router and returns it ready to use, then call sends the request. The call method comes from the Service trait, which is why the file imports both tower::Service and tower::ServiceExt. The map_response test wraps the router in a service that adds an x-tested-by header to every response, then sends a request through the wrapped service and checks the header arrived. The last two tests show the two ways to send more than one request: build a fresh router with app() for each request, or clone one router and hand the clone to the first oneshot. Cloning a Router is cheap because the route table is shared behind reference-counted pointers, so either way is fine.
Ready and map_response Need the Request Type Spelled Out:
A Router implements Service for two different request types, HTTP requests and incoming TCP streams, so a bare .ready() or .map_response() call cannot tell which one the test means and the compiler stops with error E0283, type annotations needed. The fix is the qualified form shown above, tower::ServiceExt::<Request<Body>>::ready(&mut router), which names the HTTP request type explicitly. Plain .oneshot(...) does not need this, because the request value passed to it pins the type down.
Waiting for Readiness With ready
ready exists for services that are not always able to accept a request. A rate limiter, a connection pool, or a buffer with a full queue may need a moment before the next request can go in, and poll_ready is the signal that the moment has arrived. For a plain Router with no middleware, readiness is immediate, so the await on ready resolves at once and the test reads like ceremony. The ceremony earns its place when a layer is added that can say "not yet". A test that calls ready first and call second works the same whether the service is always ready or sometimes busy, and the same two lines are the correct way to drive any Tower service by hand.
The borrow matters. ready takes &mut self, so the router stays owned by the test and can be used again after the call. That is the difference from oneshot, which consumes the router and ends its life. When a test must send three requests through one router without rebuilding it, ready plus call is the shape, with one ready await before each call.
Changing Responses With map_response
map_response takes a closure, a small anonymous function, that receives each response and returns a changed one. The closure in the example inserts a header and returns the response unchanged otherwise. The wrapped service has the same request type as the original, and its response type is whatever the closure returns, so chaining works: map_response returns a service, and oneshot can be called on that service because ServiceExt is implemented for all services, including wrapped ones.
Real uses in tests go beyond stamping headers. A closure can record the status of every response into a shared counter, strip a header the test wants to ignore, or rewrite a body for comparison. The rule is that the closure must be quick and must not fail. It runs inside the request handling, and a panic there fails the test the same way a panic in a handler would.
Sending More Than One Request
oneshot consumes the service, so a test that needs two responses has two options, and both appear in the richer example. Calling app() again builds a second router from scratch, which is simple and always correct. Cloning the router with .clone() shares the route table and is equally correct. The wrong option is reusing the moved value, which the compiler rejects with a "use of moved value" error. The error names the move, and the fix is one of the two options above.
The ready plus call form is the third option, and it keeps one router alive across many requests without cloning. It is more code per request, so tests use it only when the service must stay alive for a reason, such as a layer holding state across requests. For ordinary route tests, fresh routers or clones are simpler.
How a Request Travels Through the Trait
The diagram below follows one test request from the test function to the handler and back. Every step happens inside the test process.
Test builds Request with Request::builder()
|
v
ServiceExt::oneshot waits for poll_ready
|
v
Router matches the path and method
|
v
Handler runs and returns a value or an AppError
|
v
IntoResponse turns the return value into a Response
|
v
oneshot future resolves with Ok(response)
|
v
Test asserts on status, headers, or body
The trait owns only the first two steps and the last one. Routing, handling, and response building belong to Axum and to the app, and they run exactly as they would for a request that arrived over the network. That is what makes the test trustworthy. It does not simulate the app. It runs the app.
Testing the Trait Itself
The test file in the richer example is the testing section for this page, and it covers the trait from three angles. The oneshot tests prove a request reaches the router and a response comes back. The ready test proves the two-step form works and that call is available once the trait is imported. The map_response test proves the adapter methods wrap a service and the wrapped service still answers requests. All five tests passed against the scratch project with axum 0.8.9, tower 0.5.3, and tokio 1.54.1, and the full run is shown in the richer example above. Run them with cargo test --test service_ext_test to run just this file, or cargo test to run the whole suite.
Common Beginner Mistakes
Forgetting the util feature
# Wrong - ServiceExt does not exist without the feature
[dev-dependencies]
tower = "0.5"
Without features = ["util"], the tower crate compiles but the ServiceExt trait is not built, and the import fails with an unresolved import error. The fix is the dev-dependency line from the smallest example. The same trap applies to the filter feature for filter and filter_async, which need features = ["filter"] in addition.
A Missing Feature Looks Like a Missing Crate:
The error for a missing feature says the trait cannot be found, which reads like the crate is absent. Check the features list first. The crate is usually present and the feature is usually the missing piece.
Forgetting the import
// Wrong - oneshot is not a method on Router without the trait in scope
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
Without use tower::ServiceExt;, the compiler reports no method named oneshot found for Router. The fix is the import line. The same applies to ready and map_response, which also come from the trait.
Reusing a router after oneshot
// Wrong - the first oneshot moved the router
let router = app();
let first = router.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()).await.unwrap();
let second = router.oneshot(Request::builder().uri("/books/1").body(Body::empty()).unwrap()).await.unwrap();
The first oneshot consumes router, so the second line fails with a "use of moved value" error. The fix is to call app() again for the second request or to clone the router before the first call, as the richer example shows.
Forgetting to await the future
// Wrong - the request never runs, and the future is dropped
let response = app().oneshot(Request::builder().uri("/").body(Body::empty()).unwrap());
assert_eq!(response.status(), StatusCode::OK);
oneshot returns a future, and a future does nothing until it is awaited. Without .await, the request never runs, response is a future rather than a Result, and the status check does not compile. The compiler also warns about an unused future. The fix is .await before .unwrap(), exactly as every example on this page shows.
Calling ready without the qualified path
// Wrong - the compiler cannot tell which Service implementation is meant
let mut router = app();
let router = router.ready().await.unwrap();
This fails with error E0283, type annotations needed, because Router implements Service for HTTP requests and for TCP streams. The fix is the qualified form tower::ServiceExt::<Request<Body>>::ready(&mut router), which names the HTTP request type. The same fix applies to map_response, map_request, and the other adapters when they are called on a bare Router.
Final Complete Example
Here is everything from this page in one place: the project file, the test file with all five tests, and the commands to run them.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5.3", features = ["util"] }
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::{Service, ServiceExt};
#[tokio::test]
async fn oneshot_sends_one_request_and_returns_the_response() {
let response = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn ready_then_call_does_what_oneshot_does_in_two_steps() {
let mut router = app();
let router = tower::ServiceExt::<Request<Body>>::ready(&mut router)
.await
.unwrap();
let request = Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap();
let response = router.call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn map_response_can_add_a_header_to_every_response() {
let service = tower::ServiceExt::<Request<Body>>::map_response(app(), |mut response: axum::response::Response| {
response
.headers_mut()
.insert("x-tested-by", "service-ext".parse().unwrap());
response
});
let response = service
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers().get("x-tested-by").unwrap(),
"service-ext"
);
}
#[tokio::test]
async fn oneshot_consumes_the_router_so_each_request_needs_its_own() {
let first = app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(first.status(), StatusCode::OK);
let second = app()
.oneshot(
Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
#[tokio::test]
async fn a_cloned_router_works_for_a_second_oneshot() {
let router = app();
let first = router
.clone()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(first.status(), StatusCode::OK);
let second = router
.oneshot(
Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
Run the file with:
cargo test --test service_ext_test
All five tests pass, and the app itself never started a server.
Summary
The trait is small, and its value is leverage. One import and one feature flag turn a Router from something that only answers network requests into something a test can call directly, and the methods it adds cover the whole range from a single throwaway request to a wrapped service that records or changes every response. The decision rule is simple: reach for oneshot when a test needs one request and one answer, reach for ready plus call when the service must stay alive across requests, and reach for an adapter like map_response when the test needs to observe or change what passes through. The detail that catches beginners is not the trait itself but the two things it needs to work at all, the util feature in Cargo.toml and the use tower::ServiceExt; line in the test file. With those two in place, the router stops being a server component and becomes an ordinary value a test can drive, and that shift is what makes the rest of this cluster of pages possible.