rust - 如何在 rust 中测试异步函数?
问题描述
我有一个需要测试的异步函数。这个函数使用一个mongodb::Database
对象来运行。所以我在setup()
函数中初始化了连接,并用它tokio_test::block_on()
来包装await
里面的表达式。这是我的代码:
#[cfg(test)]
mod tests {
use mongodb::{options::ClientOptions, Client};
use tokio_test;
async fn setup() -> mongodb::Database {
tokio_test::block_on(async {
let client_uri = "mongodb://127.0.0.1:27017";
let options = ClientOptions::parse(&client_uri).await;
let client_result = Client::with_options(options.unwrap());
let client = client_result.unwrap();
client.database("my_database")
})
}
#[test]
fn test_something_async() { // for some reason, test cannot be async
let DB = setup(); // <- the DB is impl std::future::Future type
// the DB variable will be used to run another
// async function named "some_async_func"
// but it doesn't work since DB is a Future type
// Future type need await keyword
// but if I use await-async keywords here, it complains
// error: async functions cannot be used for tests
// so what to do here ?
some_async_func(DB);
}
}
解决方案
只需替换#[test]
为#[tokio::test]
任何测试功能。如果您使用 actix-web,您可以在测试函数中Cargo.toml
和之前添加 actix_rt#[actix_rt::test]
#[tokio::test]
fn test_something_async() { // for some reason, test cannot be async
let DB = setup(); // <- the DB is impl std::future::Future type
// the DB variable will be used to run another
// async function named "some_async_func"
// but it doesn't work since DB is a Future type
// Future type need await keyword
// but if I use await-async keywords here, it complains
// error: async functions cannot be used for tests
// so what to do here ?
some_async_func(DB);
}
推荐阅读
- shell - 为什么有些命令行参数和它们的标签在一起?
- java - 如何在 Azure 存储文件共享上上传大文件?
- json - MarkLogic:列出目录中的所有 JSON,并使用元数据转换为另一种 JSON 格式
- xml - XSLT 变量不充当节点集
- c# - 路由事件只能应用于从定义类派生的类型
- excel - 为什么传递参数会产生错误argumenttype ByRef?
- javascript - 使用 Sequelize 从多个表中获取数据
- javascript - 为什么这个脚本只能在主 HTML 文件中工作?
- git - 如何在没有管理员权限的情况下检测 VSCode 上的 git
- google-bigquery - GitHub 数据中缺少 mediawiki 项目?