GGistDev

Testing in Rust

Rust’s testing tools are built into the language and Cargo.

Unit tests

// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 { a + b }

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn adds_numbers() { assert_eq!(add(2,2), 4); }
}

Run with cargo test.

Integration tests

Place tests in tests/ as separate crates.

// tests/api.rs
use mycrate::add;
#[test]
fn it_works() { assert_eq!(add(1,3), 4); }

Doc tests

Examples in documentation are compiled and run.

/// Adds two numbers.
///
/// # Examples
/// ```
/// assert_eq!(mycrate::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }

Fixtures and setup

Use helper functions or modules; #[ctor]/once_cell can help with global setup if needed, but prefer per‑test setup.

Assertions and idioms

  • assert!, assert_eq!, assert_ne!
  • #[should_panic] for panic tests
  • Result in tests enables ?
#[test]
fn fallible() -> anyhow::Result<()> { Ok(()) }

Tips

  • Keep tests fast and independent
  • Use trait boundaries to inject fakes instead of complex mocks
  • Organize by feature; prefer integration tests for black‑box behavior