pub async fn call_and_read_body_json<S, B, T>(app: &S, req: Request) -> Twhere
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
    T: DeserializeOwned,
Expand description

Helper function that returns a deserialized response body of a TestRequest

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_add_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 req = test::TestRequest::post()
        .uri("/people")
        .header(header::CONTENT_TYPE, "application/json")
        .set_payload(payload)
        .to_request();

    let result: Person = test::call_and_read_body_json(&mut app, req).await;
}

Panics

Panics if:

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