unit-testing - 测试不编译 : "the async keyword is missing from the function declaration"

标签 unit-testing testing rust rust-tokio

我正在尝试在我的项目中进行工作测试 (src/subdir/subdir2/file.rs):

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

并得到这个错误编译:

error: the async keyword is missing from the function declaration
   --> src\domain\models\product.rs:185:11
    |
185 |     async fn test_format_str() {
    |           ^^

error: aborting due to previous error

这对我来说毫无意义,因为存在异步。

我最初的计划是这样的:

#[cfg(test)]
mod tests {
    #[test]
    fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

由于所有测试都不是异步的,但会产生相同的错误:

error: the async keyword is missing from the function declaration
   --> src\domain\models\product.rs:185:5
    |
185 |     fn test_format_str() {
    |     ^^

error: aborting due to previous error

我正在使用 tokio = { version = "0.2.22", features = ["full"]},从 src/main.rs 导出宏。

我试过使用 test::test;获取 std 测试宏,但这会产生不明确的导入编译错误。

我查看了这篇文章 Error in Rust unit test: "The async keyword is missing from the function declaration"但据我所知,它没有解决我的问题,我需要宏导出。

完整的可重现示例。 Win10,rustc 1.46.0。 只是一个 main.rs:

#[macro_use]
extern crate tokio;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    async fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

只有一个依赖:

[dependencies]
tokio = { version = "0.2.22", features = ["full"]}

删除

#[macro_use]
extern crate tokio;

并使用 tokio 宏作为 tokio::ex。东京::尝试加入!解决了眼前的问题,尽管很高兴知道为什么会发生这种情况。

最佳答案

这是 tokio_macros 版本 0.2.4 和 0.2.5 中的错误。以下最小示例也无法构建:

use tokio::test;

#[test]
async fn it_works() {}

根本问题在于此测试宏扩展到的代码。在目前发布的版本中,大致是这样的:

#[test]
fn it_works() {
    tokio::runtime::Builder::new()
        .basic_scheduler()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async { {} })
}

注意 #[test] 属性。它旨在引用标准 test 属性,即普通测试函数标记,但是,由于 tokio::test 在范围内,它被再次调用 -而且,由于新函数不是异步的,它会抛出一个错误。

问题已通过 this commit 修复,其中 test 替换为 ::core::prelude::v1::test,即显式地从 core 拉入。但是相应的更改还没有进入已发布的版本,我怀疑这不会很快,因为这在技术上是一个重大更改 - 增加了最低限度支持的 Rust 版本。
目前,唯一的解决方法似乎不是显式地或通过 macro_usetokio 使用通配符导入,而是显式地 使用 任何你需要的东西。

关于unit-testing - 测试不编译 : "the async keyword is missing from the function declaration",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64086896/

相关文章:

c++ - 我在使用纯虚拟方法和 Google Mock 时做错了什么?

python - Django Formset 缺少管理表单数据

python - 如何测试数据检索模块?

testing - 点击下载按钮后等待页面加载

string - 生成字符串和识别子字符串非常慢

overloading - 我怎样才能近似方法重载?

c++ - 具有许多测试的 CMake 单元结构

java - 在 spock 单元测试规范中传递实际参数

c# - 如何检查 FakeItEasy 是否一定发生了对任何重载的调用?

rust - `next()` 是移动还是克隆元素?