Avatar ·

如何正确测试 Rust 中 Tokio 的异步函数?

你好!我开始学习 Rust 和 Tokio 进行异步编程。写了一个简单的网络模块,但不知道如何正确编写异步函数的测试。 以下是我的代码示例: ```rust use tokio::time::{sleep, Duration}; pub async fn fetch_data(url: &str) -> Result { // 模拟网络请求 sleep(Duration::from_millis(100)).await; if url.is_empty() { return Err("URL 为空".to_string()); } Ok(format!("来自 {} 的数据", url)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_fetch_data() { let result = fetch_data("https://example.com"); // 这里出现编译错误 } } ``` 当我尝试运行测试时,编译器报错:`the trait bound '(): futures::Future' is not satisfied`。我理解异步函数返回 Future,需要某种方式执行它们,但不知道如何做。 我尝试在测试中添加 `await`,但那样需要将测试函数改为异步。