Learn Axum · 12/13

Testing Your Axum Application

8 min read

Welcome back, Rustacean! 🦀

So, you’ve built a blazing fast API with Axum. It compiles! The borrow checker has finally stopped screaming at you. You are ready to deploy on a Friday afternoon, right?

Wrong.

Just because it compiles doesn't mean it does what it’s supposed to do. It just means you didn't manage to segfault the memory. Now we need to ensure that when a user sends a POST /pizza, they actually get a pizza, not a 500 Internal Server Error because you forgot to handle gluten-free crusts.

Today we are diving into Testing.


1. The Testing Philosophy: Unit vs Integration Tests in Axum

Definition

Testing is the practice of executing your code automatically to verify that it functions as expected.
Unit Testing verifies the smallest testable parts of an application (like a single function) in isolation.
Integration Testing verifies that different parts of the system (like your Router, Database, and JSON extractor) work together correctly.

The Problem

You have a handler function that calculates the price of a cart.

  1. Scenario A (Unit): You want to check if 10 + 10 = 20. You don't need a web server for this.
  2. Scenario B (Integration): You want to check if sending a JSON body {"item": "apple"} to /cart actually returns 200 OK.

If you only do Scenario A, you might miss that your Router is configured to reject JSON. If you only do Scenario B, your tests run slower because they have to simulate HTTP requests.

The Solution: The Axum Approach

In the industry, testing Axum apps usually leans heavily on Integration Testing (or "Request/Response" testing).

Why? Because Axum handlers often take Extractors (like Json<T>, State<S>, Path<String>) as arguments. Constructing these complex types manually just to unit test a single function is painful and messy.

The Strategy:

  1. Extract complex business logic (math, validation) into plain Rust functions (pure logic). Unit Test these.
  2. Test the Handlers via the Router using simulated HTTP requests. Integration Test these.

2. Router Testing: Using tower::ServiceExt

Definition

tower::ServiceExt is a trait provided by the tower crate (which Axum is built on). It allows us to treat our entire Axum Router as a function that takes a Request and returns a Response, without actually sending data over a network socket.

The Problem

Spinning up a real server (binding to 127.0.0.1:3000) for every test is slow. It consumes TCP ports, triggers firewall warnings, and introduces network latency. We want to test the logic of the router, not the TCP stack of the OS.

The Solution

Since an Axum Router implements Service, we can use oneshot. This method sends a single request to the router and gets a future back. It’s almost instant.

🛠️ Hands-On: Testing a "Hello World"

Note: Make sure you have tokio, tower, and http-body-util in your dev-dependencies.

toml
# Cargo.toml
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
tower = { version = "0.4", features = ["util"] }
http-body-util = "0.1"
hyper = "1.0"

The Code:

rust
use axum::{
    routing::get,
    Router,
    body::Body,
    http::{Request, StatusCode},
};
use tower::ServiceExt; // 👈 essential for 'oneshot'
use http_body_util::BodyExt; // 👈 essential for reading the body

// 1. The Application Logic
fn app() -> Router {
    Router::new().route("/", get(|| async { "Hello, Axum!" }))
}

#[tokio::test]
async fn test_hello_world() {
    // 2. Initialize the app
    let app = app();

    // 3. Build a request (No network involved! purely in-memory)
    let request = Request::builder()
        .uri("/")
        .body(Body::empty())
        .unwrap();

    // 4. Send the request through the router
    // 'oneshot' consumes the service and executes the request
    let response = app.oneshot(request).await.unwrap();

    // 5. Assert Status Code
    assert_eq!(response.status(), StatusCode::OK);

    // 6. Assert Body Content
    // We need to read the bytes from the response body
    let body = response.into_body().collect().await.unwrap().to_bytes();
    assert_eq!(&body[..], b"Hello, Axum!");
}

What happened under the hood?
The oneshot method took your request struct, pushed it into the Axum middleware chain, ran the matcher, found the handler, executed the async block, and bubbled the response back up. All inside a single process. Fast. ⚡


3. Mocking Dependencies: Simulating Database Calls in State

Definition

Mocking is creating a fake version of a complex dependency (like a Database) that returns pre-defined answers.
Dependency Injection (DI) is a pattern where you pass dependencies (like a DB connection) into your application (via State) rather than hard-coding them.

The Problem

You want to test your create_user handler.
If your test connects to the real database:

  1. You have to wipe the DB before every test (slow).
  2. If the DB server is down, your tests fail (flaky).
  3. You might accidentally delete production data if you mess up the connection string (terrifying). 😱

The Solution

We define a Rust Trait for our database operations. The app accepts anything that implements this trait.

  • In Production, we inject the real Postgres pool.
  • In Testing, we inject a "Mock" struct that just returns "Success" without doing anything.

We will use the mockall crate, which is the industry standard for generating mocks in Rust.

🛠️ Hands-On: Dependency Injection

1. Add mockall:

toml
[dev-dependencies]
mockall = "0.12"

2. Define the Architecture:

rust
use axum::{
    extract::State,
    routing::get,
    Router,
    Json,
    http::StatusCode,
};
use std::sync::Arc;

// --- STEP 1: The Trait ---
// Define what your DB *can* do.
// automock generates a "MockDatabase" struct for us automatically in tests.
#[cfg_attr(test, mockall::automock)]
pub trait Database: Send + Sync {
    fn get_user_name(&self, user_id: i32) -> Option<String>;
}

// --- STEP 2: The Real Implementation ---
struct RealDatabase; 
impl Database for RealDatabase {
    fn get_user_name(&self, _id: i32) -> Option<String> {
        // Imagine real SQL query here
        Some("Real Postgres User".to_string())
    }
}

// --- STEP 3: The App State ---
// We use Arc<dyn Database> to allow dynamic dispatch (swapping real for mock)
#[derive(Clone)]
struct AppState {
    db: Arc<dyn Database>,
}

// --- STEP 4: The Handler ---
async fn get_user(
    State(state): State<AppState>,
) -> (StatusCode, String) {
    // The handler doesn't know if it's using a Real DB or a Mock!
    match state.db.get_user_name(1) {
        Some(name) => (StatusCode::OK, name),
        None => (StatusCode::NOT_FOUND, "User not found".to_string()),
    }
}

// --- STEP 5: The Test ---
#[cfg(test)]
mod tests {
    use super::*;
    use tower::ServiceExt;
    use axum::body::Body;
    use axum::http::Request;
    use http_body_util::BodyExt;

    #[tokio::test]
    async fn test_get_user_found() {
        // A. Create the Mock
        let mut mock_db = MockDatabase::new(); // Struct created by macro!
        
        // B. Configure expectations (The Magic ✨)
        // "I expect get_user_name to be called with arg '1', exactly once."
        // "When called, return Some('Mock User')."
        mock_db
            .expect_get_user_name()
            .with(mockall::predicate::eq(1))
            .times(1)
            .returning(|_| Some("Mock User".to_string()));

        // C. Create State with the Mock
        let state = AppState {
            db: Arc::new(mock_db),
        };

        // D. Create Router
        let app = Router::new()
            .route("/user", get(get_user))
            .with_state(state);

        // E. Send Request
        let request = Request::builder()
            .uri("/user")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        
        // F. Verification
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"Mock User");
    }
}

Why is this cool?
You verified the handler logic handles "Found" and "Not Found" scenarios correctly without touching a single database table.


4. End-to-End Tests: Spinning Up a Test Server

Definition

End-to-End (E2E) Testing involves treating the application as a "Black Box." You spin up the actual server on a real port and use a real HTTP client (like reqwest) to hit it.

The Problem

oneshot is great, but it bypasses the OS network stack. Sometimes bugs hide in the socket binding, or in middleware that only runs on actual TCP connections, or you simply want to ensure the final binary behaves correctly.

The Solution

We use tokio::spawn to run the Axum server in the background during the test.
Tip: Bind to port 0. The OS will automatically assign an available random port, so your tests never clash (e.g., "Address already in use" errors).

🛠️ Hands-On: The Real Deal

rust
use axum::{routing::get, Router};
use std::net::SocketAddr;
use tokio::net::TcpListener;

#[tokio::test]
async fn test_server_e2e() {
    // 1. Setup Router
    let app = Router::new().route("/ping", get(|| async { "pong" }));

    // 2. Bind to port 0 (Random Port)
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    
    // 3. Get the assigned port so our client knows where to call
    let addr = listener.local_addr().unwrap();

    // 4. Spawn the server in the background
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    // 5. Use a real HTTP Client (reqwest)
    let client = reqwest::Client::new();

    let response = client
        .get(format!("http://{}/ping", addr))
        .send()
        .await
        .unwrap();

    // 6. Assertions
    assert_eq!(response.status(), 200);
    let text = response.text().await.unwrap();
    assert_eq!(text, "pong");
}

Real Life Scenario:
This is how you test things like File Uploads, WebSocket connections, or strict Timeout middleware, where the physical network behavior actually matters.


📝 Summary Checklist

  1. Unit Tests: For pure math/validation logic unrelated to HTTP.
  2. Integration (Router) Tests: Use tower::ServiceExt::oneshot. This is your bread and butter. Fast and reliable.
  3. Mocking: Use mockall and Arc<dyn Trait> in State to decouple your DB.
  4. E2E Tests: Spawn on port 0 and use reqwest for the final sanity check.

Now go forth and write tests so you can deploy on Fridays without fear! 🚀


🔗 References & Further Reading

Challenge

You are given an array of user objects. Each object contains id, name, age, and email properties.

Your task is to write the body of the processUserData function to perform a series of data transformations.

  1. First, filter the initial array to keep only the user objects where the age is 18 or greater.
  2. Next, from the resulting filtered array, create a new array that contains only the email string of each user.
  3. Finally, use the reduce method on the array of emails to concatenate them into a single string, with each email separated by a semicolon (;).

The function must return this final concatenated string.

Expected result

When your processUserData function is called with the userDatabase array, it should produce a single string containing the emails of users aged 18 and over, separated by semicolons.

scss
john.doe@example.com;peter.jones@example.com;david.brown@example.com
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.