Unit tests with #[test] and assert macros

Marcus Chen Jan 2026
1 tab
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

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

    #[test]
    fn test_add() {
        assert_eq!(add(2, 2), 4);
    }

    #[test]
    #[should_panic]
    fn test_overflow() {
        add(i32::MAX, 1);
    }
}
1 file · rust Explain with highlit

Rust's built-in test framework is simple and powerful. Mark functions with #[test], and cargo test runs them. Use assert!, assert_eq!, and assert_ne! for assertions. Tests live alongside code in the same file, typically in a #[cfg(test)] mod tests block. This keeps tests close to the implementation, making refactoring easier. For panics, use #[should_panic]. For async tests with tokio, use #[tokio::test]. The test runner captures stdout by default and shows it only on failure. You can filter tests by name, run them in parallel or serial, and generate coverage reports. I write unit tests for all public APIs and edge cases. The fast feedback loop encourages test-driven development.