Rust

Unit Tests with #[test] and assert_eq!

admin by @admin ADMIN
just now
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Tests live alongside the code they test. `cargo test` runs every `#[test]` function. Use `#[cfg(test)] mod tests` so the test code is compiled out of release builds.
Rust
Raw
pub fn add(a: i32, b: i32) -> i32 { a + b }

pub fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
    if b == 0 { Err("divide by zero") } else { Ok(a / b) }
}

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

    #[test]
    fn adds_positive_numbers() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn handles_negative_numbers() {
        assert_eq!(add(-2, -3), -5);
    }

    #[test]
    fn divide_by_zero_returns_error() {
        let result = divide(10, 0);
        assert!(matches!(result, Err("divide by zero")));
    }

    #[test]
    #[should_panic(expected = "explicit panic")]
    fn panics_on_bad_input() {
        panic!("explicit panic");
    }

    #[test]
    #[ignore]
    fn slow_integration_test() {
        // run with: cargo test -- --ignored
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.