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
Back to the full Rust cheat sheet