Test async workflows
Quick answer
Async tests run futures inside an executor and check behavior without relying on arbitrary real-time sleeps. Tokio supports test runtimes and simulated time.
Test outcomes and controlled time
Use #[tokio::test] for an async test. The test-util feature allows a current-thread test runtime with start_paused = true; Tokio's clock can advance to pending timer deadlines when no work is ready. This does not control std::time::Instant or external services. Use explicit messages or completion handles to coordinate tests rather than guessing task scheduling from delays.
#[tokio::test]async fn returns_total() { let task = tokio::spawn(async { 2 + 5 }); assert_eq!(task.await.unwrap(), 7);}Manual local Rust/Cargo candidate; not executed. Expected behavior:
cargo test: one passing test.The assertion waits for the task result.
#[tokio::test(start_paused = true)]async fn timeout_without_real_wait() { use std::{future::pending, time::Duration}; let result = tokio::time::timeout(Duration::from_secs(60), pending::<()>()).await; assert!(result.is_err());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
cargo test: one passing test; simulated time reaches the timeout.The test checks the timeout contract without intentionally waiting sixty wall-clock seconds.
Common mistake
Do not make tests pass by increasing arbitrary sleep durations; assert the actual state transition.
Try it yourself
Add a test where an immediate future finishes within the same simulated timeout.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Test async workflows — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A Tokio test uses a paused clock. Which timing source does it control?
Test async workflows — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[tokio::test] async fn returns_total() { let task = tokio::spawn(async { 2 + 5 }); assert_eq!(task.await.unwrap(), 7); } ``` Which outcome or interpretation best matches this example?
Test async workflows — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[tokio::test(start_paused = true)] async fn timeout_without_real_wait() { use std::{future::pending, time::Duration}; let result = tokio::time::timeout(Duration::from_secs(60), pending::<()>()).await; assert!(result.is_err()); } ``` Which outcome or interpretation best matches this example?