Skip to main content

read_response_json

Function read_response_json 

Source
pub async fn read_response_json<T, E>(
    app: &Pipeline<Request, Response, E>,
    req: Request,
) -> T
where T: DeserializeOwned, E: 'static,
Expand description

Helper function that returns a deserialized response body of a TestRequest

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

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

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

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

    let req = test::TestRequest::post()
        .uri("/people")
        .header(header::CONTENT_TYPE, "application/json")
        .payload(payload)
        .to_request();

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