Unchanged Behavior After Splitting the Entry Point

How to verify that splitting the entry point does not change application behavior.

After you split a single-file Axum application into separate main.rs and lib.rs files, the code looks different, but the running server should behave exactly as it did before. This page explains what "unchanged behavior" means, how to confirm it, and what can go wrong during the refactor.

What Unchanged Behavior Means

A refactor is a change to the structure of code without changing what the code does. You moved the router construction out of main.rs into a function called app inside lib.rs. The routes, handlers, and responses are the same. The only difference is where the code lives.

Unchanged behavior means that if you started the server before the split and after the split, a request to any route would give you the same response. Same status code, same body, same headers. The user of your API cannot tell that you changed the project structure.

Why This Check Matters

When you move code around, it is easy to introduce small mistakes that change how the application behaves. For example:

  • You might forget to make the app function public, so main.rs cannot use it.
  • You might accidentally rename a route while copying it.
  • You might lose a piece of state or middleware because it stayed in main.rs instead of moving into lib.rs.
  • You might return the wrong type from the app function, causing a compile error that forces you to change logic.

By explicitly checking for unchanged behavior, you catch these mistakes early. You confirm that the refactor was purely structural and did not break anything.

The Starting Point: Before and After

Here is a concrete example. Before the split, a minimal Axum application might have a single src/main.rs that looks like this:

// src/main.rs - before the split
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, world!" }))
        .route("/health", get(|| async { "OK" }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

After the split, you have a thin src/main.rs and a src/lib.rs that contains the app function.

// src/main.rs - after the split
use my_app::app;
#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}
// src/lib.rs - after the split
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Hello, world!" }))
        .route("/health", get(|| async { "OK" }))
}

The structure changed, but the two routes and their handlers are identical. If you run cargo run in both versions and visit http://localhost:3000/, you will see the same text.

Verifying Unchanged Behavior Manually

The most direct way to check that nothing changed is to run the application and send requests to every route you had before. Use a browser, curl, or any HTTP client.

Start the server:

cargo run

In another terminal, test the routes:

curl http://localhost:3000/
# Output: Hello, world!
curl http://localhost:3000/health
# Output: OK

If these outputs match what you saw before the refactor, the behavior is unchanged for these routes.

Check Passed:

If every route returns the expected response, your refactor preserved the application's external behavior. The split was successful.

Automating the Verification

Manual testing is fine for a small number of routes, but a more reliable approach is to write an automated test that mounts the app and sends requests to it. This test will fail if the behavior changes in the future, giving you an early warning.

Axum provides testing utilities that let you call the router without starting a real TCP server. You can use tower::ServiceExt::oneshot to send a request and get a response.

Add this test in src/lib.rs (or in a separate test module):

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt; // for `oneshot`
    #[tokio::test]
    async fn test_root_route_returns_hello_world() {
        let app = app();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"Hello, world!");
    }
    #[tokio::test]
    async fn test_health_route_returns_ok() {
        let app = app();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"OK");
    }
}

Run the tests with:

cargo test

If both tests pass, you have automated proof that the routes still return the expected responses. The output ends with a line like this:

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Test Dependencies:

The tower crate is already a dependency of Axum, but you may need to add it to Cargo.toml explicitly to use ServiceExt in your tests. Add tower = "0.5" to your [dependencies] or [dev-dependencies].

Common Mistakes That Change Behavior

When refactoring, it is possible to accidentally change behavior. Here are the most frequent ones and how to spot them.

Forgetting to Make app Public

If you define fn app() in lib.rs without pub, main.rs cannot call it. The compiler will show an error. That is a compile-time failure, not a runtime behavior change, but it is important to fix.

// Wrong: missing pub
fn app() -> Router { ... }

The error will be something like function app is private. Fix by adding pub.

Accidentally Changing a Route Path

Copying code by hand can introduce typos. For example, you might type /helath instead of /health. The application compiles, but a request to /health now returns 404 instead of 200. Automated tests catch this immediately.

Losing Middleware or State

If your original main.rs added middleware with .layer() or state with .with_state(), you must include those in the app function in lib.rs. Forgetting to move them means the routes lose that functionality. Here is a small but complete example. The middleware is a function that checks for a header, and the state is a struct that holds a greeting message. Both are defined in the same file, so the snippet stands on its own:

// src/lib.rs
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
#[derive(Clone)]
pub struct AppState {
    pub greeting: String,
}
async fn auth_middleware(req: Request, next: Next) -> Result<Response, StatusCode> {
    if req.headers().contains_key("x-api-key") {
        Ok(next.run(req).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}
async fn handler() -> &'static str {
    "Hello, world!"
}
pub fn app() -> Router {
    let shared_state = AppState {
        greeting: "Hello, world!".to_string(),
    };
    Router::new()
        .route("/", get(handler))
        .layer(middleware::from_fn(auth_middleware))
        .with_state(shared_state)
}

The app function builds the state value, attaches the middleware with .layer, and hands the state over with .with_state. Every piece that lived in the original main.rs now lives here, in the same order.

If you leave out .layer, protected routes become accessible; if you leave out .with_state, the code will not compile at all - a router that still needs state has type Router<AppState>, and only Router<()> implements the Service trait that axum::serve requires. There is no runtime 500 to debug: the compiler stops you first.

Check State and Middleware:

Always compare the original router construction with the new app function line by line. Confirm that every .route, .layer, .nest, .with_state, and other builder method is present.

Returning the Wrong Type

The app function must return Router, not Router<SomeState> or something else. If the original router was Router<AppState> before with_state, after with_state it becomes Router<()>. The app function should return the final type that can be passed to axum::serve. For a simple app without state, Router is the same as Router<()>. If you accidentally change the return type, the compiler may give a confusing error. Stick to Router for the return type of app().

Not Including All Routes

If your original app had five routes and you only move three into lib.rs, the other two are gone. Requests to those paths now return 404. To avoid this, create a checklist of routes from the original main.rs and verify each one is present in app.

A Systematic Verification Process

Use this step-by-step process after any refactor to confirm unchanged behavior.

1

Step 1: Run the original version

Before you start refactoring, run the original single-file application and manually test every route. Write down the expected response for each one (status code, body).

2

Step 2: Refactor into lib.rs

Create lib.rs, move the router construction into pub fn app() -> Router, and update main.rs to call app(). Compile and fix any errors.

3

Step 3: Run the new version

Run cargo run and test the same routes again. Compare the responses to your notes from Step 1.

4

Step 4: Write automated tests

Add tests that send requests to app() and assert on the expected responses. Run cargo test.

5

Step 5: Confirm all tests pass

If both manual and automated checks pass, the behavior is unchanged. The refactor is complete.

Never Skip Verification:

Skipping the verification step can lead to subtle bugs that only appear later. A route that returns 404 instead of 200 might not be noticed until a user complains. Always test after refactoring.

Comparing Responses Systematically

Manual checks work when you have two or three routes. Once the list grows, write the expected answer for every route down before you refactor, then check each one off. A small table keeps the comparison honest:

RouteMethodExpected statusExpected body
/GET200Hello, world!
/healthGET200OK

Add one row per route, including routes that need headers or a body. A route you forgot to write down is a route you forgot to check.

There is one more trap: the original version may already be gone by the time you want to compare. If your project uses git, save the working version first with a commit, or use git stash to set the old code aside while you refactor. That way you can always run the old server again and compare its real responses with the new ones, instead of comparing against your memory of what they were.

What the Split Buys You Long Term

Even though the behavior remains identical, the split into main.rs and lib.rs brings significant long-term benefits. It separates the entry point from the application definition, making it easier to add tests, reuse the app in different contexts (like integration tests or documentation), and eventually split the router into multiple modules. The goal of this refactor is not to change what the app does, but to make the code easier to maintain and extend.

Summary

A refactor is only finished when you can prove nothing changed, and the proof you need depends on the size of the app. With one or two routes, a written-down list of expected responses and a few curl calls are enough. Once routes, middleware, or state enter the picture, that manual check stops scaling: write the oneshot tests instead, and keep them in the project so the next refactor gets the same safety net for free. The pattern to carry forward is simple. Before you move code, record what the app does. After you move it, compare. The compiler catches the structural mistakes, like a missing pub or forgotten state. Only a real request, or a test that sends one, catches the silent ones, like a mistyped path or a dropped route. When both kinds of check pass, the split is invisible to everyone using the API, and the code is ready to grow into separate modules for routes, handlers, and models.