Testing
With the test-client feature, ApiRouter::test_client(state) returns a client that calls your routes in memory. No port, no server, no HTTP library.
[dev-dependencies]
axum-autodoc = { version = "0.2", features = ["test-client"] }Call a route
Call test_client on the router before finish, with the state the router needs:
fn client() -> TestClient {
let state = AppState::new(
UserService::new(Arc::new(InMemoryUserRepo::default())),
JwtKeys::hs256(b"test-secret").unwrap(),
);
api(None).test_client(state)
}#[tokio::test]
async fn creates_and_finds_a_user() {
let client = client();
let created = client
.post("/users")
.json(&json!({ "name": "Ann", "email": "ann@example.com" }))
.send()
.await;
assert_eq!(created.status(), StatusCode::CREATED);
let id = created.json::<Value>()["id"].as_str().unwrap().to_string();
let found = client.get(&format!("/users/{id}")).send().await;
assert_eq!(found.status(), StatusCode::OK);
assert_eq!(found.json::<Value>()["email"], "ann@example.com");
}get, post, put, patch, delete, head and options start a request, and request(method, path) takes any method. A request has these builders:
| Builder | Sends |
|---|---|
json(&value) | a JSON body |
form(&value) | an application/x-www-form-urlencoded body |
text(..), bytes(..) | a plain body |
query(&value) | the value as query parameters, appended to the path |
header(name, value) | a header |
bearer(token) | Authorization: Bearer .. |
send().await answers with a TestResponse: status(), header(name), headers(), text(), bytes() and json::<T>().
Every status is checked
The client knows what the router documents. If a route answers with a status its operation does not list, send panics and names the route, so a handler that starts returning a new status fails the test until the documentation says so:
#[tokio::test]
async fn deleting_needs_a_token() {
let client = client();
let path = "/users/6f0c6d6e-0000-4000-8000-000000000000";
assert_eq!(
client.delete(path).send().await.status(),
StatusCode::UNAUTHORIZED
);
let token = client
.post("/auth/token")
.json(&json!({ "name": "admin" }))
.send()
.await
.json::<Value>()["token"]
.as_str()
.unwrap()
.to_string();
assert_eq!(
client.delete(path).bearer(&token).send().await.status(),
StatusCode::NOT_FOUND
);
}A route that is not in the document, such as a hidden one, and an operation that documents no responses are not checked. A default response accepts any status. Call unchecked() on the client to turn the check off.
The client panics instead of returning an error, since it is for tests.
Headers and cookies
Set them with header, as the example does for the session routes:
#[tokio::test]
async fn reads_the_session_from_headers_and_cookies() {
let reply = client()
.get("/session")
.header("x-request-id", "req-12345")
.header("cookie", "sid=abcdef123; theme=2")
.send()
.await;
assert_eq!(reply.status(), StatusCode::OK);
assert_eq!(reply.json::<Value>()["sid"], "abcdef123");
assert_eq!(reply.json::<Value>()["request_id"], "req-12345");
}Compiled out
With AXUM_AUTODOC_ENABLED=false there is no document to check against, so the client calls the router and skips the status check.