Cargo Test

View saved

Add a test module

Mark test functions with #[test]. Put them in a #[cfg(test)] module.

fn add(a: i32, b: i32) -> i32 {
    a + b
}

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

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

Run tests

Cargo discovers and runs tests in the package.

cargo test

Assert helpers

  • assert! for boolean checks
  • assert_eq! and assert_ne! for comparisons
  • Tests fail on panic
  • Integration tests can live in a tests/ directory

Testing tips

Keep functions pure when you can so tests stay simple. Prefer checking public behavior over private details.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.