expression
REST: assert the error contract
Test missing resources as well as successful responses. This in-memory endpoint models a single stored item and returns a stable problem category for other IDs. The problem URI is illustrative. The example verifies selected status and body properties. Standalone synthetic example. Expected stdout (not executed): missing item contract matched Common mistake: Testing only the happy path.
Formal Syntax & Structure
rust syntaxrust
assert_eq!(response.status(), StatusCode::NOT_FOUND)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, response::IntoResponse}; let app = Router::new().route("/items/{id}", get(|Path(id): Path<u32>| async move { if id == 7 { Json(serde_json::json!({"id":7,"name":"pen"})).into_response() } else { (StatusCode::NOT_FOUND, [("content-type", "application/problem+json")], Json(serde_json::json!({"type":"about:blank","title":"Not Found","status":404}))).into_response() } })); let res = app.oneshot(Request::builder().uri("/items/8").body(Body::empty()).unwrap()).await.unwrap(); assert_eq!(res.status(), StatusCode::NOT_FOUND); assert_eq!(res.headers()["content-type"].to_str().unwrap(), "application/problem+json"); let data: serde_json::Value = serde_json::from_slice(&to_bytes(res.into_body(), 1024).await.unwrap()).unwrap(); assert_eq!(data["status"], 404); println!("missing item contract matched");}