如何在actix_web单元测试中获取响应的主体? [英] How to get the body of a Response in actix_web unit test?
问题描述
我正在使用 Rust 和 actix_web 构建一个 Web API 服务.
I'm building a web API service with Rust and actix_web.
我想测试一条路由并检查收到的响应正文是否符合我的预期.但是我正在努力将接收到的正文 ResponseBody
转换为 JSON 或 BSON.被调用的路由实际上返回application/json
.
I want to test a route and check if the received response body is what I expect. But I'm struggling with converting the received body ResponseBody<Body>
into JSON or BSON. The called route actually returns application/json
.
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, JSON, or BSON. The response is actually application/json.
推荐答案
actix/examples 存储库通过定义一个新特征并在 ResponseBody
类型上实现它以在可能的情况下将其内容作为 &str
返回来实现这一点:
The actix/examples repository achieves this by defining a new trait and implementing it on the ResponseBody<Body>
type to return its content as a &str
when possible:
trait BodyTest {
fn as_str(&self) -> &str;
}
impl BodyTest for ResponseBody<Body> {
fn as_str(&self) -> &str {
match self {
ResponseBody::Body(ref b) => match b {
Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
_ => panic!(),
},
ResponseBody::Other(ref b) => match b {
Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
_ => panic!(),
},
}
}
}
之后你可以简单地做:
assert_eq!(resp.response().body().as_str(), "Your name is John");
这些摘录的完整代码参考来自:https://github.com/actix/examples/blob/master/forms/form/src/main.rs
Reference to full code these excerpts were taken from: https://github.com/actix/examples/blob/master/forms/form/src/main.rs
这篇关于如何在actix_web单元测试中获取响应的主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!