Function actix_web::test::read_body_json

source ·
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> Twhere
    B: MessageBody,
    T: DeserializeOwned,
Expand description

Helper function that returns a deserialized response body of a ServiceResponse.

Examples

use actix_web::{App, test, web, HttpResponse, http::header};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Person {
    id: String,
    name: String,
}

#[actix_web::test]
async fn test_post_person() {
    let app = test::init_service(
        App::new().service(
            web::resource("/people")
                .route(web::post().to(|person: web::Json<Person>| async {
                    HttpResponse::Ok()
                        .json(person)})
                    ))
    ).await;

    let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();

    let res = test::TestRequest::post()
        .uri("/people")
        .header(header::CONTENT_TYPE, "application/json")
        .set_payload(payload)
        .send_request(&mut app)
        .await;

    assert!(res.status().is_success());

    let result: Person = test::read_body_json(res).await;
}

Panics

Panics if:

  • body yields an error while it is being read;
  • received body is not a valid JSON representation of T.