#[test]展开描述
将 async 函数标记为由运行时执行,适用于测试环境。该宏帮助设置一个 Runtime,
无需用户直接使用
Runtime 或
Builder。
注意:该宏被设计为简单易用,面向不需要复杂配置的应用。如果所提供的功能不够用, 您可以考虑使用 Builder,它提供更强大的接口。
§多线程运行时
要使用多线程运行时,可通过以下方式配置该宏:
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn my_test() {
assert!(true);
}worker_threads 选项用于配置 worker 线程数量,
默认为系统上的 CPU 数量。
注意:多线程运行时需要 rt-multi-thread 特性标志。
§当前线程运行时
默认的测试运行时是单线程的。每个测试 使用独立的当前线程运行时。
#[tokio::test]
async fn my_test() {
assert!(true);
}§用法
§Set the name of the runtime
#[tokio::test(name = "my-test-runtime")]
async fn my_test() {
assert!(true);
}不使用 #[tokio::test] 的等价代码
#[test]
fn my_test() {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.name("my-test-runtime")
.build()
.unwrap()
.block_on(async {
assert!(true);
})
}§Using the multi-thread runtime
#[tokio::test(flavor = "multi_thread")]
async fn my_test() {
assert!(true);
}不使用 #[tokio::test] 的等价代码
#[test]
fn my_test() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
assert!(true);
})
}§Using current thread runtime
#[tokio::test]
async fn my_test() {
assert!(true);
}不使用 #[tokio::test] 的等价代码
#[test]
fn my_test() {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
assert!(true);
})
}§Set number of worker threads
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn my_test() {
assert!(true);
}不使用 #[tokio::test] 的等价代码
#[test]
fn my_test() {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap()
.block_on(async {
assert!(true);
})
}§Configure the runtime to start with time paused
#[tokio::test(start_paused = true)]
async fn my_test() {
assert!(true);
}不使用 #[tokio::test] 的等价代码
#[test]
fn my_test() {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.start_paused(true)
.build()
.unwrap()
.block_on(async {
assert!(true);
})
}注意:start_paused 需要启用 test-util 特性。
§Rename package
use tokio as tokio1;
#[tokio1::test(crate = "tokio1")]
async fn my_test() {
println!("Hello world");
}§Configure unhandled panic behavior
可用选项包括 shutdown_runtime 和 ignore。更多详情请参阅
Builder::unhandled_panic。
此选项仅与 current_thread 运行时兼容。
#[cfg(tokio_unstable)]
#[tokio::test(flavor = "current_thread", unhandled_panic = "shutdown_runtime")]
async fn my_test() {
let _ = tokio::spawn(async {
panic!("This panic will shutdown the runtime.");
}).await;
}
不使用 #[tokio::test] 的等价代码
#[cfg(tokio_unstable)]
#[test]
fn my_test() {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.unhandled_panic(UnhandledPanic::ShutdownRuntime)
.build()
.unwrap()
.block_on(async {
let _ = tokio::spawn(async {
panic!("This panic will shutdown the runtime.");
}).await;
})
}
注意:此选项依赖于 Tokio 的不稳定 API。关于如何启用 Tokio 不稳定特性的详情,请参阕不稳定特性相关文档。