如何测试使用Tokio的异步函数?

72

我有一个需要测试的异步函数。这个函数使用一个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);
    }
}

8
在编写异步测试时,请使用 #[tokio::test] 而不是 #[test] - Ivan C
它解决了我的问题。只需添加 #[tokio::test],突然间我的测试函数就可以接受 await 了。如果你使用 actix-web,你可以在 Cargo.toml 中添加 actix_rt,并在测试函数前加上 #[actix_rt::test] - DennyHiu
1个回答

104

只需在任何测试函数之前将#[test]替换为#[tokio::test]。如果您使用actix-web,可以将actix_rt添加到Cargo.toml中,并在测试函数之前添加#[actix_rt::test]

#[tokio::test]
async fn test_something_async() {
    let DB = setup().await; // <- 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).await;
}

7
如果我从函数名中省略了 async 关键字:error: the async keyword is missing from the function declaration。如果函数名中省略了 async 关键字,则会出现错误信息:error: the async keyword is missing from the function declaration - rustyMagnet
2
@rustyMagnet 只需要在 fn 前面加上 async,即 async fn test_something_async() - vim
1
谢谢,这正是我所需要的! - Stephen Blum
5
小提示,您必须在tokio crate上启用“宏”功能。 - melMass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接