我有一个异步函数需要测试.此函数使用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,可以在测试功能之前将actix\u rt添加到Cargo.toml#[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);
}

Rust相关问答推荐

使用windows crate Rust 展示windows

为什么要在WASM库中查看Rust函数需要`#[no_mangle]`?

Rust TcpStream不能在读取后写入,但可以在不读取的情况下写入.为什么?

如何在Bevy/Rapier3D中获得碰撞机的计算质量?

为什么Rust函数的移植速度比C++慢2倍?

无法理解铁 rust &S错误处理

在执行其他工作的同时,从共享裁判后面的VEC中删除重复项

有没有一种惯用的方法来判断VEC中是否存在变体?

在生存期内将非静态可变引用转换为范围内的静态可变引用

如何防止Cargo 单据和Cargo 出口发布( crate )项目

Tokio';s io::用Cursor拆分<;Vec<;u8>>;赢得';t get the full writted data

使用启用优化的 alloc 会导致非法指令崩溃

Google chrome 和 Apple M1 中的计算着色器

闭包返回类型的生命周期规范

无法将`&Vec>`转换为`&[&str]`

Rust 生命周期:这两种类型声明为不同的生命周期

判断对象是 PyDatetime 还是 Pydate 的实例?

使用方法、关联函数和自由函数在 Rust 中初始化函数指针之间的区别

当特征函数依赖于为 Self 实现的通用标记特征时实现通用包装器

为什么在使用 self 时会消耗 struct 而在解构时不会?