【问题标题】:Getting error "expected function" when trying to call function from a unit test尝试从单元测试调用函数时出现错误“预期函数”
【发布时间】:2022-11-30 04:13:49
【问题描述】:

我正在尝试为 Actix Web 函数编写一个简单的单元测试用例,但是在尝试从测试函数调用该函数时出现错误。我得到的错误是:E0618: expected function, found <my function name>

我试过完全按照 Actix website 上建议的方式来称呼它。

这是一个代码示例:

use actix_web::{get, web, Responder, Result};
use serde::Serialize;

#[derive(Serialize, Debug)]
struct PingResponse {
    status: String,
}

#[get("/ping")]
async fn health_check() -> Result<impl Responder> {
    //web::Json<PingResponse> {
    let resp = PingResponse {
        status: "alive".to_string(),
    };

    Ok(web::Json(resp))
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::test;

    #[actix_web::test]
    async fn test_ping_ok() {
        let req = test::TestRequest::default().to_http_request();

        // E0618 expected function, found `health::health_check`
        let resp = health_check(req).await;

        // E0618: expected function, found `health_check`
        // let resp = crate::apis::health::health_check(req);

        assert_eq!(resp.status(), "alive".to_string());
    }
}

我试过只使用函数名和完全限定的函数名来调用 health_check 函数。

诊断消息是:

error[E0618]: expected function, found `apis::health::health_check`
  --> src/apis/health.rs:29:20
   |
9  | #[get("/ping")]
   | --------------- `apis::health::health_check` defined here
...
29 |         let resp = health_check(req).await;
   |                    ^^^^^^^^^^^^-----
   |                    |
   |                    call expression requires function

【问题讨论】:

  • 该功能是否需要公开?
  • 您确定在对它们应用 #[get(...)] 操作后可以直接调用它们吗?我的猜测是他们完全被提升为另一件事。记住这些宏可以基本上在编译之前改变你的代码。您可能想要做的是在您的测试中设置一个服务器,然后发出一个正常的 GET 请求,除非有更好的方法来进行集成测试。
  • 我怀疑 #[get("/ping")] 让它看起来像一个结构。我想我应该可以打电话。无需单元测试即可按预期编译和工作。
  • 它“有效”是因为 Actix 期望该路由在内部是任何东西,而不仅仅是一个函数。该函数本身被重写并包装在其他东西中。我不确定它是否可以直接调用,你需要通过路由层。并不是说它看起来像一个结构,它是一个在宏完成时。
  • 您可以使用 cargo expand 之类的内容查看您的代码发生了什么。

标签: unit-testing rust rust-actix


【解决方案1】:

我可以看到该函数没有返回我认为它是什么,而是一个结构。我找到了几个解决方案:

  1. 删除 #[get("/ping")] 属性并从 http 服务器设置中进行路由。这使我可以从单元测试中正常调用该函数。

  2. 使用test::TestRequest::get() 然后执行app.call(req) 来进行通用调用。这样我就可以将路由留在功能上。

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2017-05-08
    • 2022-01-24
    • 1970-01-01
    • 2020-07-31
    • 2016-10-01
    相关资源
    最近更新 更多