Testing - Handler Unit Tests

1. Welcome and Icebreaker:

What’s the most surprising bug you’ve ever found with a unit test?

2. Outline the Session:

Agenda:

  1. Concept Explanation: Why and how to unit test Axum handlers.
  2. Live Coding: Write unit tests for handler logic.
  3. Tasks: Practice by testing your own handlers.

Learning Outcomes:

  • Understand the value of unit testing in Axum projects.
  • Write and run unit tests for handler functions.

Expectations: Try writing tests for both success and error cases!

3. Concept Explanation:

Unit tests check the smallest parts of your code in isolation. In Axum, you can test handler logic by separating it from Axum-specific types, or by mocking dependencies like AppState.

4. Live Coding Demonstration:

Put this at the bottom of src/main.rs in the Day 1 example, where hello is defined (or rename hello() to root() if you kept its original name):

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_hello_handler() {
        let response = root().await;
        assert_eq!(response, "Hello, Axum!");
    }
}

Best Practices:

  • Keep handler logic pure for easier testing.
  • Use mocks for state or database dependencies.

Common Pitfalls:

  • Tightly coupling handlers to Axum types.
  • Not testing error cases.

5. Tasks

  • Write a unit test for a handler that returns an error.
  • Refactor a handler to make it easier to test.
  • Try mocking AppState or other dependencies in your tests.