Skip to main content

Test

// src/lib.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}

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

#[test]
fn it_works() -> Result<(), String> {
if 2 + 2 == 4 {
Ok(())
} else {
Err(String::from("Plus result is not four"))
}
}

#[test]
fn test_can_hold() {
let r1 = Rectangle {width: 8, height: 7};
let r2 = Rectangle {width: 5, height: 1};
assert!(r1.can_hold(&r2));
assert!(!r2.can_hold(&r1));
}
}

Unit test

  • Use #[cfg(test)] to annotate the mod, then it won't be run in cargo build.
  • Ussually use tests as the module name.

Integration test

  • Put all the tests in the folder tests. No need to add #[cfg(test)].

Cargo test

# stop hiding output
cargo test -- --nocapture