撰寫測試

測試的重要性

撰寫測試是工程師負責任的表現,也是安穩入眠的秘訣。一套完善的測試不僅能提升程式碼品質,預防回歸錯誤,更能讓你在部署後高枕無憂。當同事深夜收到系統崩潰的警報時,你的應用卻穩若磐石,這正是測試帶來的寧靜與自信。

Salvo測試工具

Salvo 提供的 test 模組,能協助測試 Salvo 專案。

最新文件

簡易範例:

use salvo::prelude::*;

#[handler]
async fn hello_world() -> &'static str {
    "Hello World"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    tracing::info!("Listening on http://127.0.0.1:5800");
    let acceptor = TcpListener::new("127.0.0.1:5800").bind().await; Server::new(acceptor).serve(route()).await;
}

fn route() -> Router {
    Router::new().get(hello_world)
}

#[cfg(test)]
mod tests {
    use salvo::prelude::*;
    use salvo::test::{ResponseExt, TestClient};

    #[tokio::test]
    async fn test_hello_world() {
        let service = Service::new(super::route());

        let content = TestClient::get(format!("http://127.0.0.1:5800/"))
            .send(&service)
            .await
            .take_string()
            .await
            .unwrap();
        assert_eq!(content, "Hello World");
    }
}