Rust Tutorial: Testing
Write unit tests with #[test], use assert macros, and organise tests in Rust.
Built-in testing
Rust has first-class testing support built into the language. No external frameworks needed for unit tests.
Run tests with `cargo test`.
What you'll learn in this Rust testing tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Your first test — Mark a function with `#[test]` to make it a test. The test passes if it does not panic.
- assert! macro — `assert!` checks that a condition is true.
- assert_ne! — `assert_ne!` checks that two values are NOT equal.
- Custom failure messages — All assert macros accept an optional format string for better error messages.
- #[should_panic] — Mark a test with `#[should_panic]` when it should panic to pass.
- Test organisation in mod tests — Convention: put tests in a `mod tests` block with `#[cfg(test)]`.
- Result in tests — Tests can return `Result<(), E>` — return Err to fail, Ok(()) to pass.
- Test-driven development — Write the test first, watch it fail, then implement the function.
Rust Testing concepts covered
- Built-in testing