expression

REST: assert a successful response contract

A contract test should observe the public HTTP boundary rather than private implementation details. Use an in-memory router to check status, content type and promised fields. This selected-field assertion is intentionally smaller than full OpenAPI validation. Standalone synthetic example. Expected stdout (not executed): contract matched Common mistake: Asserting only the status and missing an incompatible JSON body.

Formal Syntax & Structure

rust syntaxrust
app.oneshot(request).await; assert_eq!(status, 200)

Working Example

Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{extract::Path, routing::get};    let app = Router::new().route("/items/{id}", get(|Path(id): Path<u32>| async move { Json(serde_json::json!({"id":id,"name":"pen"})) }));    let res = app.oneshot(Request::builder().uri("/items/7").body(Body::empty()).unwrap()).await.unwrap();    assert_eq!(res.status(), StatusCode::OK);    assert_eq!(res.headers()["content-type"].to_str().unwrap(), "application/json");    let data: serde_json::Value = serde_json::from_slice(&to_bytes(res.into_body(), 1024).await.unwrap()).unwrap();    assert_eq!(data["id"], 7); assert_eq!(data["name"], "pen");    println!("contract matched");}
Rust Reference