JSON body assertions

Learn how to read an Axum test response body with to_bytes parse it with serde_json and assert on fields whole values arrays and error bodies

A JSON body assertion is the check that the body of a response holds the JSON the test expects. The status says which outcome the handler chose, and the body says what the handler produced. The check has three steps: read the body bytes with axum::body::to_bytes, parse the bytes into a serde_json::Value with serde_json::from_slice, and compare a field or the whole value with assert_eq!. Its one job is to prove the response carries the right data, not just the right status.

Where This Fits

The status assertion page checked the outcome of each request, and every test there stopped after the status. This page reads the rest of the response. A 200 with the wrong book is a passing status and a broken app, and only the body check catches it. The body is where the data lives, and this page is about reading it, parsing it, and comparing it in the ways that stay readable as the app grows.

Think of a letter. The envelope says who it is for, and the letter inside says what the sender wants. The status is the envelope, and the body is the letter. Checking the envelope proves the letter arrived at the right address. Reading the letter proves it says the right thing.

The Smallest Working Version

The smallest body assertion is a test that asks for one book and checks the exact body text. 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.

tests/json_body_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn body_text(response: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

#[tokio::test]
async fn book_body_matches_exactly() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        body_text(response).await,
        r#"{"id":1,"title":"The Rust Book"}"#
    );
}

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, and serde_json as a regular dependency, because the tests parse JSON with it.

Cargo.toml
[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 book_body_matches_exactly ... ok

The body_text helper does the reading. response.into_body() takes the body out of the response, axum::body::to_bytes collects the body stream into one chunk of bytes, usize::MAX is the size limit, and String::from_utf8 turns the bytes into text. The test asserts the status first, then the body text, in that order. The exact text is {"id":1,"title":"The Rust Book"}, with no spaces, because that is exactly what the Json responder writes.

Working Setup:

If cargo test prints ok for this test, the body helper works: the bytes are read, the text is built, and the exact body matches.

Understanding the Body Reading Line by Line

The helper is short, and each call in it has a job a beginner should see once.

Taking the body out of the response

response.into_body()

A Response holds a head and a body. The head carries the status and the headers, and the body carries the bytes. into_body() consumes the response and returns just the body. Consuming matters. After this call the response is gone, which is why the status must be asserted before the helper runs. The body type is axum::body::Body, a stream of byte chunks that can only be read once.

Collecting the stream into bytes

axum::body::to_bytes(response.into_body(), usize::MAX)

axum::body::to_bytes is an async function that reads every chunk of the body stream and joins them into one Bytes value. It takes the body and a size limit, and usize::MAX is the largest possible limit, which means "do not stop early". The limit exists so a test against a huge response cannot eat all memory by accident, and the maximum value turns the protection off for tests where the body is known to be small. The call returns a future, so the helper awaits it, and the future resolves to a Result, so the helper unwraps it. A body that fails mid-stream would make the result an Err, and in a test that failure is a panic, which is the right outcome, because a response that cannot be read is a broken response.

Turning bytes into text

String::from_utf8(bytes.to_vec()).unwrap()

Bytes is a reference-counted byte buffer, and .to_vec() copies its contents into an owned Vec<u8>. String::from_utf8 turns the byte vector into a String, and it fails if the bytes are not valid UTF-8. JSON is always valid UTF-8, so the unwrap is safe for JSON bodies. For a body that is not text, such as an image, this step would fail, and the test should keep the bytes instead of turning them into a string.

The Concept Behind Parsing Instead of Comparing Text

The smallest example compares the exact body text, and that comparison is brittle in one specific way. JSON objects have no defined key order, and two JSON texts with the same data in a different order are equal as JSON and unequal as text. The book struct serialises its fields in declaration order, id then title, so the exact text is stable for this app, but a test that depends on that order depends on an accident of the struct layout. Parsing the body into a Value and comparing values removes the order from the comparison entirely.

serde_json::Value is the type for arbitrary JSON data. It has variants for objects, arrays, strings, numbers, booleans, and null, and indexing a value with a string key reads a field out of an object. The helper below is the parsed form, and it is the form most tests on this page use.

tests/json_body_test.rs
use serde_json::Value;

async fn body_json(response: axum::response::Response) -> Value {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    serde_json::from_slice(&bytes).unwrap()
}

serde_json::from_slice parses the bytes into a Value and returns a Result, which the helper unwraps. A body that is not valid JSON makes the parse fail, and the unwrap panics with the parse error, which is a clear failure message. The helper shares the first three lines with body_text, and the two helpers differ only in the last step: text keeps the bytes as a string, and JSON parses them into a value.

Why the Body Is Read Once

A response body is a stream, and a stream is consumed as it is read. The first read drains it, and a second read finds nothing left. That is why the helpers take the response by value and return the text or the parsed value. A test cannot call body_text and then call body_json on the same response, because the first call ate the body. The test must choose one form per response, or read the bytes once and derive both from the bytes. The rule is simple: one response, one body read, and the status assertions come first because the status survives the read.

The Error Body Shape

Every error in the app uses the same body shape, one object with one key, {"error": message}, and the message depends on the variant. The mapping is the one the error pages built: a missing book gives 404 with {"error":"resource not found"}, a validation failure gives 422 with the message the handler supplied, an internal failure gives 500 with {"error":"something went wrong"}, a duplicate email gives 409 with {"error":"email already in use"}, a missing token gives 401 with {"error":"unauthorized"}, and a wrong role gives 403 with {"error":"forbidden"}. The tests on this page assert the full error body for the first four, and the layout page asserts the last two. The point of asserting the body and not just the status is that the body proves the message travelled with the status. A 404 with the wrong message is a test failure the status check alone would miss.

A Richer Complete Example

The smallest version checked one exact body. A realistic test file checks bodies in every form a test needs: exact text, a single field, the whole value, a created resource, all four error bodies, an array, a missing field, and the content type header. The file uses three helpers, one per body form, and two request helpers that hide the request building.

tests/json_body_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use serde_json::{Value, json};
use tower::ServiceExt;

async fn body_bytes(response: axum::response::Response) -> axum::body::Bytes {
    axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap()
}

async fn body_json(response: axum::response::Response) -> Value {
    let bytes = body_bytes(response).await;
    serde_json::from_slice(&bytes).unwrap()
}

async fn body_text(response: axum::response::Response) -> String {
    let bytes = body_bytes(response).await;
    String::from_utf8(bytes.to_vec()).unwrap()
}

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 book_body_matches_exactly() {
    let response = get("/books/1").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        body_text(response).await,
        r#"{"id":1,"title":"The Rust Book"}"#
    );
}

#[tokio::test]
async fn book_title_is_read_from_parsed_json() {
    let json = body_json(get("/books/1").await).await;
    assert_eq!(json["title"], "The Rust Book");
    assert_eq!(json["id"], 1);
}

#[tokio::test]
async fn whole_body_equals_the_expected_json_value() {
    let json = body_json(get("/books/1").await).await;
    assert_eq!(json, json!({"id": 1, "title": "The Rust Book"}));
}

#[tokio::test]
async fn created_book_body_holds_the_sent_title() {
    let json = body_json(post_json("/books", r#"{"title":"Dune"}"#).await).await;
    assert_eq!(json["id"], 2);
    assert_eq!(json["title"], "Dune");
}

#[tokio::test]
async fn missing_book_error_body_is_the_fixed_message() {
    let response = get("/books/99").await;
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(
        body_json(response).await,
        json!({"error": "resource not found"})
    );
}

#[tokio::test]
async fn validation_error_body_keeps_the_message() {
    let response = post_json("/books", r#"{"title":""}"#).await;
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(
        body_json(response).await,
        json!({"error": "title must not be empty"})
    );
}

#[tokio::test]
async fn internal_error_body_hides_the_cause() {
    let response = get("/boom").await;
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(
        body_json(response).await,
        json!({"error": "something went wrong"})
    );
}

#[tokio::test]
async fn conflict_error_body_names_the_duplicate() {
    let response = post_json(
        "/register",
        r#"{"email":"ada@example.com","name":"Ada"}"#,
    )
    .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);
    assert_eq!(
        body_json(response).await,
        json!({"error": "email already in use"})
    );
}

#[tokio::test]
async fn list_body_is_a_json_array_with_two_books() {
    let json = body_json(get("/books").await).await;
    let books = json.as_array().unwrap();
    assert_eq!(books.len(), 2);
    assert_eq!(books[0]["title"], "The Rust Book");
    assert_eq!(books[1]["title"], "Dune");
}

#[tokio::test]
async fn a_missing_field_is_null_not_a_panic() {
    let json = body_json(get("/books/1").await).await;
    assert!(json["author"].is_null());
    assert!(json.get("author").is_none() || json["author"].is_null());
}

#[tokio::test]
async fn response_content_type_is_json() {
    let response = get("/books/1").await;
    let content_type = response
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(content_type.starts_with("application/json"));
}

Run it with cargo test, and all eleven tests pass:

test a_missing_field_is_null_not_a_panic ... ok
test book_body_matches_exactly ... ok
test book_title_is_read_from_parsed_json ... ok
test conflict_error_body_names_the_duplicate ... ok
test created_book_body_holds_the_sent_title ... ok
test internal_error_body_hides_the_cause ... ok
test list_body_is_a_json_array_with_two_books ... ok
test missing_book_error_body_is_the_fixed_message ... ok
test response_content_type_is_json ... ok
test validation_error_body_keeps_the_message ... ok
test whole_body_equals_the_expected_json_value ... ok

The body_bytes helper is the shared base, and body_json and body_text build on it, so the reading logic lives in one place. The field test shows the most common assertion shape: parse the body, index one field, compare it. The whole-value test shows the strongest shape: build the expected JSON with the json! macro and compare the two values, which checks every field at once and ignores key order. The array test shows .as_array(), which turns a Value into a slice of values or panics when the body is not an array, and then indexes the elements like any other list. The content type test reads a header off the response before the body is consumed, because headers live in the head and survive, and it checks the value starts with application/json rather than equaling it exactly, because the responder may add a charset suffix.

Three Helpers Cover Every Body Check:

body_bytes reads once, body_json parses, and body_text keeps the text. A test picks the helper that matches what it wants to check, and no test reads a body twice. Put the three helpers in the shared test module the layout page describes, and every test file in the suite can use them.

Comparing One Field

The field assertion is the workhorse. json["title"] reads the title field out of the object, and assert_eq! compares it to the expected string. The comparison works because Value implements PartialEq against string literals and numbers, so the test writes the expected value directly without converting it. The field test checks two fields, the title and the id, and a test that needs more fields adds more lines in the same shape. The weakness is that an unchecked field can drift without any test noticing, which is why the whole-value test exists alongside it.

Comparing the Whole Value

The whole-value assertion builds the expected JSON with the json! macro, a macro from serde_json that writes JSON inline in Rust code, and compares it to the parsed body with one assert_eq!. The macro form looks like JSON itself, with keys in quotes and values in place, so the expected value is easy to read and easy to change. The comparison ignores key order, because Value equality compares objects by their keys and not by their order. The tradeoff is that the test breaks whenever any field changes, even a field the test does not care about, so whole-value assertions belong on small, stable responses like a single book or an error body, and field assertions belong on large responses where only a few fields matter.

Reading Arrays

A list response parses into a Value whose variant is an array, and .as_array() returns Some with the elements or None when the body is not an array. The test unwraps it and then checks the length and the elements by index. The index order is the order the handler produced, and for the book list that order is the store order, id 1 then id 2. An array test that only checks the length proves the count, and a test that also checks the elements proves the contents. Both are worth writing, because a handler that returns two wrong books passes a length-only test.

Reading a Missing Field

Indexing a Value with a missing key does not panic. It returns Value::Null, the JSON null value, and .is_null() reports true for it. The test shows both spellings: json["author"].is_null() and json.get("author"), which returns None for a missing key. The two spellings differ in what they check. The index form cannot tell a missing field from a field that is present with a null value, and the get form can, because it returns None only when the key is absent. A test that must prove a field is absent uses get, and a test that only needs the value to be null uses the index form.

Checking the Content Type

The content type header says what format the body is in, and the Json responder sets it to application/json. The test reads it with response.headers().get("content-type"), which returns an Option, unwraps it, and converts the header value to a string with .to_str(). The assertion uses starts_with instead of equality, because the header value may carry a suffix such as a charset, and the test cares about the format, not the suffix. The header must be read before the body is consumed, or rather it can be read at any time, because headers live in the response head, but the test reads it first out of habit, and the habit keeps the order consistent across tests.

What Happens With a Body That Is Not JSON

A test that calls body_json on a plain-text response fails at the parse step. The home route returns the text Hello from the test app!, and serde_json::from_slice rejects it with a parse error, which the helper unwrap turns into a panic. The panic message names the parse failure, and the fix is to use body_text for text responses and body_json for JSON responses. The two helpers exist because the two body kinds need different treatment, and picking the wrong helper is a test bug, not an app bug.

How a Body Assertion Travels

The diagram below follows one body assertion from the response to the verdict.

Handler returns Json(value) or an AppError
        |
        v
IntoResponse serialises the value to JSON bytes
        |
        v
oneshot resolves with Ok(response)
        |
        v
Test asserts the status first
        |
        v
into_body takes the body stream out of the response
        |
        v
to_bytes collects the stream into Bytes
        |
        v
from_slice parses the bytes into a Value
        |
        v
assert_eq compares a field or the whole value

The status assertion and the body assertion are two halves of one verdict. The status says the handler chose the right outcome, and the body says it produced the right data. A test that checks both proves the response end to end.

Testing the Assertions Themselves

The test file in the richer example is the testing section for this page. It covers body assertions from eleven angles: exact text, one field, the whole value, a created resource, four error bodies, an array, a missing field, and the content type. All eleven tests passed against the scratch project with axum 0.8.9, tower 0.5.3, and tokio 1.54.1, and every error body asserted matches the error mapping the earlier chapters taught. Run them with cargo test --test json_body_test to run just this file, or cargo test to run the whole suite.

Common Beginner Mistakes

Reading the body twice

// Wrong - the first read consumes the body, the second finds nothing
let text = body_text(response).await;
let json = body_json(response).await;

This fails to compile, because body_text takes the response by value and the second call has nothing left to pass. The fix is to read the bytes once with body_bytes and derive both the text and the parsed value from those bytes, or to pick one form per response.

One Response, One Body Read:

A response body is a stream, and reading it drains it. A test that needs both the text and the parsed value reads the bytes once and converts them twice, never the response twice.

Parsing a plain-text body as JSON

// Wrong - the home route returns text, and from_slice rejects it
let json = body_json(get("/").await).await;

The home route returns Hello from the test app!, which is not JSON, so the parse fails and the helper panics. The fix is body_text for text responses, and body_json only for responses the handler built with Json.

Comparing exact text when the field order may change

// Wrong - the assertion breaks if the struct field order changes
assert_eq!(body_text(response).await, r#"{"id":1,"title":"The Rust Book"}"#);

The exact text comparison is correct for this app and brittle in general, because it depends on the serialisation order of the struct fields. The fix is the parsed comparison, assert_eq!(json, json!({"id": 1, "title": "The Rust Book"})), which ignores key order and states the expected data instead of the expected text.

Forgetting to await to_bytes

// Wrong - to_bytes returns a future, not bytes
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX);
let json: Value = serde_json::from_slice(&bytes).unwrap();

Without .await, bytes is a future, and from_slice cannot parse a future. The fix is .await on the to_bytes call, exactly as the helpers show.

Asserting the body before the status

// Wrong - the body is consumed before the status is checked
let json = body_json(response).await;
assert_eq!(response.status(), StatusCode::OK);

This fails to compile, because body_json 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 uses.

Indexing a missing field and expecting a panic

// Wrong - the index returns Null, and the test passes when it should fail
assert_eq!(json["author"], "Ada Lovelace");

This does not panic. It compares Null to the string, and the assertion fails with a clear message, which is the correct behaviour. The mistake is the expectation, not the code. A test that wants to prove a field is absent should assert json.get("author").is_none(), which states the absence directly.

Final Complete Example

Here is everything from this page in one place: the test file with all eleven tests and the five helpers, and the command to run them.

tests/json_body_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use serde_json::{Value, json};
use tower::ServiceExt;

async fn body_bytes(response: axum::response::Response) -> axum::body::Bytes {
    axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap()
}

async fn body_json(response: axum::response::Response) -> Value {
    let bytes = body_bytes(response).await;
    serde_json::from_slice(&bytes).unwrap()
}

async fn body_text(response: axum::response::Response) -> String {
    let bytes = body_bytes(response).await;
    String::from_utf8(bytes.to_vec()).unwrap()
}

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 book_body_matches_exactly() {
    let response = get("/books/1").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        body_text(response).await,
        r#"{"id":1,"title":"The Rust Book"}"#
    );
}

#[tokio::test]
async fn book_title_is_read_from_parsed_json() {
    let json = body_json(get("/books/1").await).await;
    assert_eq!(json["title"], "The Rust Book");
    assert_eq!(json["id"], 1);
}

#[tokio::test]
async fn whole_body_equals_the_expected_json_value() {
    let json = body_json(get("/books/1").await).await;
    assert_eq!(json, json!({"id": 1, "title": "The Rust Book"}));
}

#[tokio::test]
async fn created_book_body_holds_the_sent_title() {
    let json = body_json(post_json("/books", r#"{"title":"Dune"}"#).await).await;
    assert_eq!(json["id"], 2);
    assert_eq!(json["title"], "Dune");
}

#[tokio::test]
async fn missing_book_error_body_is_the_fixed_message() {
    let response = get("/books/99").await;
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(
        body_json(response).await,
        json!({"error": "resource not found"})
    );
}

#[tokio::test]
async fn validation_error_body_keeps_the_message() {
    let response = post_json("/books", r#"{"title":""}"#).await;
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(
        body_json(response).await,
        json!({"error": "title must not be empty"})
    );
}

#[tokio::test]
async fn internal_error_body_hides_the_cause() {
    let response = get("/boom").await;
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(
        body_json(response).await,
        json!({"error": "something went wrong"})
    );
}

#[tokio::test]
async fn conflict_error_body_names_the_duplicate() {
    let response = post_json(
        "/register",
        r#"{"email":"ada@example.com","name":"Ada"}"#,
    )
    .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);
    assert_eq!(
        body_json(response).await,
        json!({"error": "email already in use"})
    );
}

#[tokio::test]
async fn list_body_is_a_json_array_with_two_books() {
    let json = body_json(get("/books").await).await;
    let books = json.as_array().unwrap();
    assert_eq!(books.len(), 2);
    assert_eq!(books[0]["title"], "The Rust Book");
    assert_eq!(books[1]["title"], "Dune");
}

#[tokio::test]
async fn a_missing_field_is_null_not_a_panic() {
    let json = body_json(get("/books/1").await).await;
    assert!(json["author"].is_null());
    assert!(json.get("author").is_none() || json["author"].is_null());
}

#[tokio::test]
async fn response_content_type_is_json() {
    let response = get("/books/1").await;
    let content_type = response
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(content_type.starts_with("application/json"));
}

Run the file with:

cargo test --test json_body_test

All eleven tests pass, and every body shape in the app is pinned down in one file.

Summary

The body assertion is where a test stops checking that the app answered and starts checking what it said. The three helpers are the whole toolkit: read the bytes once, parse them when the body is JSON, keep them as text when it is not. The judgement calls are about scope: a field assertion when one value matters, a whole-value assertion when the response is small and stable, an array assertion when the count and the contents both matter, and an error body assertion whenever the status alone could hide a wrong message. The habit that ties them together is order, status first, body second, one read per response. With that order, a test failure names the exact place the app and the promise parted ways, and the fix lands in the handler or the error mapping, never in the test harness.