expression

Axum: assert the JSON response contract

Test the HTTP status, media type and parsed JSON values rather than relying on object-key order or string formatting. Bound the collected body before parsing. This example checks the public response fields without touching a database. In-memory standalone Cargo example. Expected stdout (not executed): contract matches Common mistake: Comparing a JSON object as a raw string with a fixed key ordering.

Formal Syntax & Structure

rust syntaxrust
serde_json::from_slice::<Value>(&bytes)

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::{Json, routing::get, http::header};    use serde_json::{json, Value};    let app = Router::new().route("/stock", get(|| async { Json(json!({"available": 3, "sku": "A1"})) }));    let res = app.oneshot(Request::builder().uri("/stock").body(Body::empty()).unwrap()).await.unwrap();    assert_eq!(res.status(), StatusCode::OK);    assert_eq!(res.headers()[header::CONTENT_TYPE], "application/json");    let data = to_bytes(res.into_body(), 128).await.unwrap();    let value: Value = serde_json::from_slice(&data).unwrap();    assert_eq!(value, json!({"sku": "A1", "available": 3}));    println!("contract matches");}
Rust Reference