简体   繁体   中英

actix web test doesn't seem to be routing requests as expected

I recently updated to actix web 4, I had some tests that used the actix-web test module that stopped working as expected in the process. I'm sure it's something simple but I'm having trouble figuring out what changed. Here is a minimal example of the issue:

use actix_web::{test, web, App, HttpResponse, HttpRequest};

#[actix_rt::test]
async fn says_hello() {
  let req = test::TestRequest::get().uri("/index.html").to_request();
  let mut server =
    test::init_service(App::new().service(web::scope("/").route("index.html", web::get().to(|_req: HttpRequest| async {
      println!("Hello?");
      HttpResponse::Ok()
    })))).await;
  let _resp = test::call_and_read_body(&mut server, req).await;
}

running this test I would expect to see "Hello?" output to my console, however, the request handler function I have defined at "/index.html" doesn't seem to be called and I receive no output.

To be clear, the tests are more complicated and have assertions etc, this is just a working example of the main issue I am trying to resolve

actix-web = { version = "4.1.0", default-features = false }


note:

if I change all paths to the root path it will call the handler, IE

  let req = test::TestRequest::get().uri("/").to_request();
  let mut server =
    test::init_service(App::new().service(web::scope("/").route("/", web::get().to(|_req: HttpRequest| async {
      println!("Hello?");
      HttpResponse::Ok()
    })))).await;
  let _resp = test::call_and_read_body(&mut server, req).await;

  // prints "Hello?" to the console

However no other route combination I have tried calls the request handler.

Rust tests capture the output and only output them for failed tests.

If you want to show output on all tests you have to tell them to do so with either testbinary --nocapture or cargo test -- --nocapture .

I was able to make things work by changing the path in the scope to an empty string

let req = test::TestRequest::get().uri("/index.html").to_request();
let mut server =
test::init_service(App::new().service(web::scope("").route("index.html", web::get().to(|_req: HttpRequest| async {
  println!("Hello?");
  HttpResponse::Ok()
})))).await;
let _resp = test::call_and_read_body(&mut server, req).await;

// prints "Hello?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM