Response status assertions
Learn how to assert on the HTTP status of an Axum test response with StatusCode constants class helpers and the full status table for the book app
A response status assertion is the check that the status code of a response is the one the test expects. The status is the first thing a test should check, because it says which outcome the handler chose before the body says anything about it. The check is one line, assert_eq!(response.status(), StatusCode::OK), and it reads the status off the response with .status() and compares it to a named constant from the http crate. Its one job is to pin down the outcome of the request in the fewest possible words.
Where This Fits
The pages before this one built the request and sent it through the router, and every example ended with a status check. This page takes that final line apart. The request and the send are the setup, and the assertion is the verdict. A test that sends the right request and checks the wrong thing proves nothing, so the status assertion earns a page of its own: which constants exist, how to compare them, and which status each outcome in the app produces.
Think of a scoreboard. The game is the handler running, and the scoreboard is the status code. The crowd does not need the full play-by-play to know who won. The score says it. The body is the play-by-play, and it comes second. The status assertion reads the scoreboard.
The Smallest Working Version
The smallest status assertion is a test that asks for an existing book and checks the status is 200. The project is the same book app from the error pages, with the app function in src/lib.rs and the AppError type in src/errors.rs.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn existing_book_returns_200() {
let response = app()
.oneshot(
Request::builder()
.uri("/books/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
The Cargo.toml file is the same project file as the ServiceExt page, with tower as a dev-dependency and the util feature turned on.
[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 it with cargo test, and it passes:
test existing_book_returns_200 ... ok
response.status() returns a StatusCode, a type from the http crate that Axum re-exports as axum::http::StatusCode. StatusCode::OK is the named constant for 200. assert_eq! compares the two values, and if they differ it prints both, so a failure reads like "left is 404, right is 200" and the test names the mismatch plainly.
Working Setup:
If cargo test prints ok for this test, the assertion works: the status is read off the response, the constant names 200, and the comparison passes.
Understanding StatusCode
StatusCode is a small wrapper around a u16, an unsigned 16-bit number, and the number is the status code itself. The type adds two things the raw number does not have. First, named constants for every standard status, so the test writes StatusCode::NOT_FOUND instead of 404 and the intent is visible in the code. Second, helper methods that classify a status, so the test can ask whether a status is a success or an error without comparing numbers.
The constants the book app uses are the common ones. StatusCode::OK is 200, the request succeeded. StatusCode::CREATED is 201, a new resource was created. StatusCode::UNAUTHORIZED is 401, the request had no credentials. StatusCode::FORBIDDEN is 403, the credentials were not enough. StatusCode::NOT_FOUND is 404, the resource does not exist. StatusCode::METHOD_NOT_ALLOWED is 405, the path exists but the method does not. StatusCode::CONFLICT is 409, the request conflicts with the current state. StatusCode::UNPROCESSABLE_ENTITY is 422, the input failed validation. StatusCode::UNSUPPORTED_MEDIA_TYPE is 415, the body format was not accepted. StatusCode::INTERNAL_SERVER_ERROR is 500, something broke inside the server. The http crate defines constants for the full standard set, and a test that needs an unusual status can build one from a number with StatusCode::from_u16(418).unwrap().
The number is available with .as_u16(), which returns the u16 inside the status. A test that asserts response.status().as_u16() == 200 compiles and passes, but it is the worse form. The number says nothing about what it means, and a reader must remember the code table to read the test. The constant form says the meaning in the code itself.
The class helpers
A StatusCode can answer four questions about itself. .is_success() is true for 200 to 299. .is_redirection() is true for 300 to 399. .is_client_error() is true for 400 to 499. .is_server_error() is true for 500 to 599. These are called class helpers, because each status class is a range of numbers with a shared meaning. A test that checks the class rather than the exact code is looser, and looseness is sometimes the point. A test for "the request failed on the client side" should pass for 404 and for 422 alike, and the class helper states that intent. A test for "the missing book returns 404" should use the exact constant, because the exact code is the behaviour being pinned down.
assert_eq and assert_ne
assert_eq! is the assertion for "these two are equal", and it prints both values when they differ. assert_ne! is the assertion for "these two are not equal", and it prints both when they are the same. Status tests use assert_eq! for the expected status and assert_ne! for the status the response must not have. Both macros take the actual value first and the expected value second by convention, so a failure message reads "left is the actual status, right is the expected status" and the reader knows which side is which.
The Concept Behind Checking the Status First
The status is the outcome, and the body is the detail. A test that checks the body first and the status second can pass on a body that looks right for the wrong reason. A 404 body for a missing book and a 200 body for an empty list can contain similar text, and only the status tells them apart. Checking the status first also fails fast. When the status is wrong, the test stops at the first assertion, and the failure message names the wrong outcome directly. When the status is right, the test moves on to the body with the outcome already confirmed.
There is a mechanical reason too. Reading the response body consumes it, and a consumed body cannot be read again. The status, by contrast, can be read as many times as the test likes, because it lives in the response head, not in the body. A test that asserts the status first never has to worry about ordering its body reads around its status checks.
The Status Table for the Book App
The app answers each outcome with a fixed status, and the table below is the contract the tests pin down. Every row comes from the error design the earlier pages built: the AppError variants map to statuses in one IntoResponse implementation, and the handlers return those variants when the matching situation arises.
| Situation | Status | Constant |
|---|---|---|
| Book exists | 200 | StatusCode::OK |
| Book created | 201 | StatusCode::CREATED |
| No token on a protected route | 401 | StatusCode::UNAUTHORIZED |
| Token present, role is not admin | 403 | StatusCode::FORBIDDEN |
| Book does not exist | 404 | StatusCode::NOT_FOUND |
| Unknown route | 404 | StatusCode::NOT_FOUND |
| Wrong method on a known route | 405 | StatusCode::METHOD_NOT_ALLOWED |
| Duplicate email on register | 409 | StatusCode::CONFLICT |
| JSON body without a content type | 415 | StatusCode::UNSUPPORTED_MEDIA_TYPE |
| Empty or overlong title | 422 | StatusCode::UNPROCESSABLE_ENTITY |
| Handler failure | 500 | StatusCode::INTERNAL_SERVER_ERROR |
Two rows share 404, and that sharing is correct. A missing book and an unknown route are both "the thing asked for does not exist", and the client cannot tell them apart from the status alone. The body differs, because the missing book carries {"error":"resource not found"} while the unknown route carries an empty body, and the body assertion page takes that difference apart. The 409 row comes from the register route, where a duplicate email conflicts with the user already stored. The 401 and 403 rows come from the admin route, where a missing token means no identity at all and a wrong role means the identity is not allowed in.
Why Constants Beat Numbers
A test that writes assert_eq!(response.status().as_u16(), 404) works, and it is still the wrong shape. The number 404 is a magic number, a literal value whose meaning lives only in the reader's memory. The constant StatusCode::NOT_FOUND carries its meaning in its name. A reader who has never seen the HTTP code table can read the constant and know what the test expects. A writer who mistypes StatusCode::NOT_FOND gets a compile error, while a writer who mistypes 404 as 440 gets a test that fails at runtime with a confusing message. The constant is checked by the compiler, and the number is not.
The same reasoning applies to from_u16. A test that needs a non-standard status, such as 418, must build it from a number, because there is no constant for it. That is the exception, and the standard statuses all have constants, so a test file for this app never needs the number form.
A Richer Complete Example
The smallest version checked one status. A realistic test file checks the whole table, one test per row, plus the class helpers and the negative assertion. The file uses two small helpers, get and post_json, that hide the request building so each test is two lines: send the request, assert the status.
use axum::{
body::Body,
http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn get(path: &str) -> axum::response::Response {
app()
.oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
.unwrap()
}
async fn post_json(path: &str, json: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.method(Method::POST)
.uri(path)
.header("content-type", "application/json")
.body(Body::from(json.to_string()))
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn existing_book_returns_200() {
let response = get("/books/1").await;
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn creating_a_book_returns_201() {
let response = post_json("/books", r#"{"title":"Dune"}"#).await;
assert_eq!(response.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn missing_book_returns_404() {
let response = get("/books/99").await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn empty_title_returns_422() {
let response = post_json("/books", r#"{"title":""}"#).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn crashing_handler_returns_500() {
let response = get("/boom").await;
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn duplicate_email_returns_409() {
let response = post_json(
"/register",
r#"{"email":"ada@example.com","name":"Ada"}"#,
)
.await;
assert_eq!(response.status(), StatusCode::CONFLICT);
}
#[tokio::test]
async fn admin_without_a_token_returns_401() {
let response = get("/admin").await;
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn admin_with_a_token_but_the_wrong_role_returns_403() {
let response = app()
.oneshot(
Request::builder()
.uri("/admin")
.header("x-token", "secret-token")
.header("x-role", "reader")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn success_statuses_report_themselves_as_success() {
let ok = get("/books/1").await;
assert!(ok.status().is_success());
assert_eq!(ok.status().as_u16(), 200);
}
#[tokio::test]
async fn error_statuses_report_their_class() {
let missing = get("/books/99").await;
assert!(missing.status().is_client_error());
assert!(!missing.status().is_success());
let broken = get("/boom").await;
assert!(broken.status().is_server_error());
assert_eq!(broken.status().as_u16(), 500);
}
#[tokio::test]
async fn the_wrong_status_fails_loudly() {
let response = get("/books/99").await;
assert_ne!(response.status(), StatusCode::OK);
}
Run it with cargo test, and all eleven tests pass:
test admin_with_a_token_but_the_wrong_role_returns_403 ... ok
test admin_without_a_token_returns_401 ... ok
test creating_a_book_returns_201 ... ok
test crashing_handler_returns_500 ... ok
test duplicate_email_returns_409 ... ok
test empty_title_returns_422 ... ok
test error_statuses_report_their_class ... ok
test existing_book_returns_200 ... ok
test missing_book_returns_404 ... ok
test success_statuses_report_themselves_as_success ... ok
test the_wrong_status_fails_loudly ... ok
Each test names the situation in its function name, so a failure in the test output reads like a sentence: missing_book_returns_404 failed means the missing book did not return 404. The two helper functions keep the request building out of the tests, and the 403 test builds its request inline because it needs headers the helpers do not set. The class tests show the two uses of as_u16(): confirming the exact number behind a class check, which is the one place the number form earns its place.
One Test Per Status Keeps Failures Readable:
A single test that asserts eleven statuses in a row stops at the first failure and hides the rest. Eleven tests, one per status, run independently, and the output names exactly which outcomes broke. The helpers make the extra tests cheap to write.
Asserting on the Class Instead of the Code
The class helpers are the right tool when the test cares about the kind of outcome and not the exact code. A test for the register route might assert that a duplicate email is a client error, without pinning the exact code, while a separate test pins 409. The two tests together say that the outcome is both in the client error class and exactly a conflict, and each test can fail independently. The class test guards the shape, and the exact test guards the detail.
The class helpers also appear in tests that loop over many inputs. A test that sends ten bad titles to the create route can assert that every response is_client_error(), and a second test can assert that each one is exactly 422. The loop test proves no input crashes the server into a 500, and the exact test proves the validation mapping is right.
Asserting the Status Before Reading the Body
The response body can be read only once, because it is a stream that is consumed as it is read. The status lives in the response head and can be read any number of times. A test that reads the body first and then checks the status still works, because the status is still there, but a test that reads the body twice fails, and the failure looks like a body problem when the real fault is the read order. The habit that avoids the whole class of mistakes is to assert the status first, then read the body. The body assertion page shows the read helpers, and every test there follows this order.
How a Status Assertion Travels
The diagram below follows one assertion from the response to the verdict.
Handler returns a value or an AppError
|
v
IntoResponse builds a Response with a status
|
v
oneshot resolves with Ok(response)
|
v
response.status() reads the StatusCode
|
v
assert_eq compares it to the expected constant
|
+-- equal --> test passes, body checks follow
|
+-- not equal --> test fails with both values printed
The status is decided by the handler and the error conversion, not by the test. The test only reads what is already there and compares it to what the app promised. That is why a status failure always means the app behaved differently from the promise, and never means the assertion itself is broken, unless the expected constant in the test is wrong.
Testing the Assertions Themselves
The test file in the richer example is the testing section for this page. It covers the table from eight angles, the class helpers from two angles, and the negative assertion from one angle. All eleven tests passed against the scratch project with axum 0.8.9, tower 0.5.3, and tokio 1.54.1, and every status asserted matches the error mapping the earlier chapters taught: 404 with "resource not found", 422 with the validation message, 500 with "something went wrong", 409 with the conflict message, 401 with "unauthorized", and 403 with "forbidden". Run them with cargo test --test status_assertions_test to run just this file, or cargo test to run the whole suite.
Common Beginner Mistakes
Comparing the status to a number
// Wrong - it works, but the meaning is hidden in a magic number
assert_eq!(response.status().as_u16(), 404);
The test passes, and the reader must remember that 404 means not found. The fix is the constant form, assert_eq!(response.status(), StatusCode::NOT_FOUND), which states the meaning in the code and is checked by the compiler.
Numbers Hide Meaning and Typos:
A mistyped number compiles and fails at runtime with a confusing message. A mistyped constant fails at compile time with the name spelled out. Use the constant everywhere a standard status is meant.
Comparing the status to a string
// Wrong - StatusCode is not a string, and this does not compile
assert_eq!(response.status(), "404");
response.status() returns a StatusCode, and assert_eq! requires both sides to have the same type. A string literal is a &str, so the comparison fails to compile. The fix is the constant, or .as_u16() on the left and a number on the right.
Asserting on the Result instead of the response
// Wrong - the Result has no status method
let response = app()
.oneshot(Request::builder().uri("/books/1").body(Body::empty()).unwrap())
.await;
assert_eq!(response.status(), StatusCode::OK);
After .await the value is a Result<Response, Infallible>, not a Response. The fix is .unwrap() after .await, which opens the result and gives the test the response to assert on.
Checking only the success case
// Wrong - half the table is untested
#[tokio::test]
async fn existing_book_returns_200() {
let response = get("/books/1").await;
assert_eq!(response.status(), StatusCode::OK);
}
This test is correct and incomplete. An app that returns 200 for every request passes it, including an app whose error paths are all broken. The fix is one test per status in the table, so a broken error path fails its own test and the output names it.
Reading the body before the status in a test that reads twice
// Wrong - the second body read finds nothing left
let text = body_text(response).await;
assert_eq!(response.status(), StatusCode::OK);
This exact code fails to compile, because body_text takes the response by value and the status line has nothing left to read. The fix is to assert the status first, then read the body, which is the order every test on this page and the body assertion page uses.
Final Complete Example
Here is everything from this page in one place: the test file with all eleven tests and the two helpers, and the command to run them.
use axum::{
body::Body,
http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn get(path: &str) -> axum::response::Response {
app()
.oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
.unwrap()
}
async fn post_json(path: &str, json: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.method(Method::POST)
.uri(path)
.header("content-type", "application/json")
.body(Body::from(json.to_string()))
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn existing_book_returns_200() {
let response = get("/books/1").await;
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn creating_a_book_returns_201() {
let response = post_json("/books", r#"{"title":"Dune"}"#).await;
assert_eq!(response.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn missing_book_returns_404() {
let response = get("/books/99").await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn empty_title_returns_422() {
let response = post_json("/books", r#"{"title":""}"#).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn crashing_handler_returns_500() {
let response = get("/boom").await;
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn duplicate_email_returns_409() {
let response = post_json(
"/register",
r#"{"email":"ada@example.com","name":"Ada"}"#,
)
.await;
assert_eq!(response.status(), StatusCode::CONFLICT);
}
#[tokio::test]
async fn admin_without_a_token_returns_401() {
let response = get("/admin").await;
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn admin_with_a_token_but_the_wrong_role_returns_403() {
let response = app()
.oneshot(
Request::builder()
.uri("/admin")
.header("x-token", "secret-token")
.header("x-role", "reader")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn success_statuses_report_themselves_as_success() {
let ok = get("/books/1").await;
assert!(ok.status().is_success());
assert_eq!(ok.status().as_u16(), 200);
}
#[tokio::test]
async fn error_statuses_report_their_class() {
let missing = get("/books/99").await;
assert!(missing.status().is_client_error());
assert!(!missing.status().is_success());
let broken = get("/boom").await;
assert!(broken.status().is_server_error());
assert_eq!(broken.status().as_u16(), 500);
}
#[tokio::test]
async fn the_wrong_status_fails_loudly() {
let response = get("/books/99").await;
assert_ne!(response.status(), StatusCode::OK);
}
Run the file with:
cargo test --test status_assertions_test
All eleven tests pass, and the whole status table for the app is pinned down in one file.
Summary
The status assertion is the smallest check in the suite and the one that carries the most information per line. One comparison states which outcome the handler chose, and the table of outcomes is the contract between the app and its clients. The habits that make the table trustworthy are three: use the named constants so the meaning is visible and compiler-checked, write one test per status so each failure names its own outcome, and assert the status before touching the body so the read order never bites. The deeper point is that the statuses are not arbitrary. They come from the error design, one variant per situation and one status per variant, so a test that pins the status is really a test that the error design holds. When the table is green, the app answers every situation the way it promised, and the body checks that follow only have to confirm the words.