How to properly test async functions with Tokio in Rust?
Hello! I started learning Rust and Tokio for asynchronous programming. I wrote a simple module for network operations, but I can't figure out how to properly write tests for async functions.
Here's an example of my code:
```rust
use tokio::time::{sleep, Duration};
pub async fn fetch_data(url: &str) -> Result {
// Simulating a network request
sleep(Duration::from_millis(100)).await;
if url.is_empty() {
return Err("URL is empty".to_string());
}
Ok(format!("Data from {}", url))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fetch_data() {
let result = fetch_data("https://example.com");
// Compilation error here
}
}
```
When I try to run the test, the compiler gives an error: `the trait bound`
No answers yet.
Log in to leave an answer