actix_web::test

Function read_body

source
pub async fn read_body<B>(res: ServiceResponse<B>) -> Bytes
where B: MessageBody,
Expand description

Helper function that returns a response body of a ServiceResponse.

§Examples

use actix_web::{test, web, App, HttpResponse, http::header};
use bytes::Bytes;

#[actix_web::test]
async fn test_index() {
    let app = test::init_service(
        App::new().service(
            web::resource("/index.html")
                .route(web::post().to(|| async {
                    HttpResponse::Ok().body("welcome!")
                })))
    ).await;

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

    let res = test::call_service(&app, req).await;
    let result = test::read_body(res).await;
    assert_eq!(result, Bytes::from_static(b"welcome!"));
}

§Panics

Panics if body yields an error while it is being read.