[英]Test does not compile: "the async keyword is missing from the function declaration"
我正在嘗試在我的項目 (src/subdir/subdir2/file.rs) 中進行工作測試:
#[cfg(test)]
mod tests {
#[tokio::test]
async fn test_format_str() {
let src = "a";
let expect = "a";
assert_eq!(expect, src);
}
}
並得到這個錯誤編譯:
error: the async keyword is missing from the function declaration
--> src\domain\models\product.rs:185:11
|
185 | async fn test_format_str() {
| ^^
error: aborting due to previous error
這對我來說毫無意義,因為 async 在那里。
我原來的計划是這樣的:
#[cfg(test)]
mod tests {
#[test]
fn test_format_str() {
let src = "a";
let expect = "a";
assert_eq!(expect, src);
}
}
由於所有測試都不是異步的,但這會產生相同的錯誤:
error: the async keyword is missing from the function declaration
--> src\domain\models\product.rs:185:5
|
185 | fn test_format_str() {
| ^^
error: aborting due to previous error
我正在使用 tokio = { version = "0.2.22", features = ["full"]},從 src/main.rs 導出宏。
我試過使用 test::test; 獲取 std 測試宏,但這會產生不明確的導入編譯錯誤。
我查看了這篇文章Rust 單元測試中的錯誤:“函數聲明中缺少 async 關鍵字”,但據我所知,它沒有解決我的問題,我需要宏導出。
完全可重現的示例。 Win10,rustc 1.46.0。 只是一個main.rs:
#[macro_use]
extern crate tokio;
#[tokio::main]
async fn main() -> std::io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
async fn test_format_str() {
let src = "a";
let expect = "a";
assert_eq!(expect, src);
}
}
具有單個依賴項:
[dependencies]
tokio = { version = "0.2.22", features = ["full"]}
刪除
#[macro_use]
extern crate tokio;
並使用 tokio 宏作為 tokio:: ex。 tokio::try_join! 解決了眼前的問題,盡管很高興知道為什么會發生這種情況。
這是tokio_macros
版本 0.2.4 和 0.2.5 中的一個錯誤。 以下最小示例也無法構建:
use tokio::test;
#[test]
async fn it_works() {}
根本問題在於此測試宏擴展到的代碼。 在目前發布的版本中,大致是這樣的:
#[test]
fn it_works() {
tokio::runtime::Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async { {} })
}
注意#[test]
屬性。 它旨在引用標准test
屬性,即普通測試函數標記,但是,由於tokio::test
在范圍內,它會再次被調用 - 而且,由於新函數不是異步的,它會引發錯誤.
此提交修復了該問題,其中test
替換為::core::prelude::v1::test
,即從core
顯式拉入。 但是相應的更改還沒有進入發布版本,我懷疑這不會很快,因為這在技術上是一個突破性的更改 - 沖擊最低支持的 Rust 版本。
目前,唯一的解決方法似乎不是明確地或通過macro_use
使用通配符導入tokio
,而是use
您需要明確的任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.