响应头中的测试内容类型



我试图在响应中运行Content-Type的集成测试。

--> testsgreet.rs:18:9
|
5   |     let response = client
|         -------- move occurs because `response` has type `Response`, which does not implement the `Copy` trait
...
13  |         response.text().await.unwrap(),
|                  ------ `response` moved due to this method call
...
18  |         response.content_length(),
|         ^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
note: this function takes ownership of the receiver `self`, which moves `response`
--> C:UsersSaurabh Mishra.cargoregistrysrcgithub.com-1ecc6299db9ec823reqwest-0.11.12srcasync_implresponse.rs:146:23
|
146 |     pub async fn text(self) -> crate::Result<String> {
|                       ^^^^

当我注释掉响应体(response.text()...)的测试时,所有测试都正确执行。

测试集是:

#[tokio::test]
async fn greeting_works() {
spawn_app();
let client = reqwest::Client::new();
let response = client
.get("http://127.0.0.1:8080/hello")
.send()
.await
.expect("Failed to execute request");
assert!(response.status().is_success(), "Endpoint validity");
assert_eq!(
response.text().await.unwrap(),
"Hello, World!",
"Response from endpoint"
);
assert_eq!(
response.content_length(),
Some(13),
"Response length is 13 characters"
);
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"text/plain; charset=utf-8"
);
}
fn spawn_app() {
let server = mailrocket::run().expect("Failed to bind address");
let _ = tokio::spawn(server);
}

如何运行此套件以执行所有四个测试?

.text()消耗响应,因此在调用该方法后不能再使用它。修复它的一个简单方法是最后执行.text()上的断言:

#[tokio::test]
async fn greeting_works() {
spawn_app();
let client = reqwest::Client::new();
let response = client
.get("http://127.0.0.1:8080/hello")
.send()
.await
.expect("Failed to execute request");
assert!(response.status().is_success(), "Endpoint validity");
assert_eq!(
response.content_length(),
Some(13),
"Response length is 13 characters"
);
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"text/plain; charset=utf-8"
);
assert_eq!(
response.text().await.unwrap(),
"Hello, World!",
"Response from endpoint"
);
}
fn spawn_app() {
let server = mailrocket::run().expect("Failed to bind address");
let _ = tokio::spawn(server);
}

相关内容

  • 没有找到相关文章

最新更新