Get Body of Response in Actix web test request in Rust

青春壹個敷衍的年華 提交于 2020-12-12 05:38:36

问题


I'm building a web api service with rust and actix.

I want to test a route and check if the received response body is what i expect. But I'm strugeling with converting the received body (ResponseBody) into a Json/Bson. The called route actually returns application/json.

Thanks for your help.

 let mut app = test::init_service(App::new()
            .data(AppState { database: db.clone() })
            .route("/recipes/{id}", web::post().to(add_one_recipe))).await;

        let payload = create_one_recipe().as_document().unwrap().clone();

        let req = test::TestRequest::post()
            .set_json(&payload).uri("/recipes/new").to_request();

        let mut resp = test::call_service(&mut app, req).await;
        let body: ResponseBody<Body> = resp.take_body(); // Here i want the body as Binary, String or Json/Bson what the response actually is (application/json)

回答1:


Having a look at Body and ResponseBody, this looks like the approach:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Greet {
    name: String,
}

async fn greet() -> impl Responder {
    let body = serde_json::to_string(&Greet {
        name: "Test".to_owned(),
    })
    .unwrap();
    HttpResponse::Ok()
        .content_type("application/json")
        .body(body)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/", web::get().to(greet)))
        .bind("127.0.0.1:8000")?
        .run()
        .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{body::Body, test, web, App};
    use serde_json::json;

    #[actix_rt::test]
    async fn test_greet_get() {
        let mut app = test::init_service(App::new().route("/", web::get().to(greet))).await;
        let req = test::TestRequest::with_header("content-type", "application/json").to_request();
        let mut resp = test::call_service(&mut app, req).await;
        let body = resp.take_body();
        let body = body.as_ref().unwrap();
        assert!(resp.status().is_success());
        assert_eq!(
            &Body::from(json!({"name":"Test"})), // or serde.....
            body
        );
    }
}
running 1 test
test tests::test_greet_get ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out


来源:https://stackoverflow.com/questions/63910673/get-body-of-response-in-actix-web-test-request-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!