Writing Tests

The Importance of Testing

Writing tests is a hallmark of responsible engineering and the secret to sleeping soundly. A comprehensive test suite not only improves code quality and prevents regression errors but also ensures you rest easy after deployment. While your colleagues might be jolted awake by late-night system crash alerts, your application remains rock-solid—this is the tranquility and confidence that testing brings.

Salvo Testing Tools

The test module provided by Salvo helps you test Salvo-based projects.

Latest Documentation

Simple Example:

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:8698");
    let acceptor = TcpListener::new("127.0.0.1:8698").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:8698/"))
            .send(&service)
            .await
            .take_string()
            .await
            .unwrap();
        assert_eq!(content, "Hello World");
    }
}