编写测试

测试的重要性

编写测试是工程师负责任的表现,也是安心睡觉的秘诀。一套完善的测试不仅能提高代码质量,防止回归错误,还能让你在部署后依然睡得香甜。当你的同事深夜收到系统崩溃的警报时,你的应用却稳如泰山,这就是测试带来的宁静与自信。

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");
    }
}