Function actix_test::read_response_json[][src]

pub async fn read_response_json<S, B, T>(
    app: &'_ S,
    req: Request<Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>> + 'static, Global>>>
) -> T where
    S: Service<Request<Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>> + 'static, Global>>>, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody + Unpin,
    T: DeserializeOwned,
    <B as MessageBody>::Error: Into<Error>, 
Expand description

Helper function that returns a deserialized response body of a TestRequest

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::read_response_json(&mut app, req).await;
}