Writing Tests in Rust
From the Rust cheat sheet ยท Testing ยท verified Jul 2026
Writing Tests
Unit tests, integration tests, and test organization.
rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(add(2, 3), 5);
}
#[test]
#[should_panic(expected = "divide by zero")]
fn panics_on_zero() {
divide(1, 0);
}
}
// Run: cargo test๐ก #[cfg(test)] ensures test code is never compiled into your release binary
โก Tests that return Result<(), E> let you use ? instead of .unwrap() โ cleaner test code
๐ Use -- --nocapture to see println! output from passing tests
๐ข Integration tests go in tests/ directory and can only access your public API
testingassertunit-tests