Rust Testing — Unit Tests, Integration Tests, Doc Tests, and Test Organization
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Testing. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust testing includes unit tests with #[cfg(test)], integration tests in tests/ directory, and doc tests in /// documentation comments.
What You'll Learn
- Unit tests with #[test]
- Integration tests
- Doc tests
- Test attributes
Why It Matters
Testing ensures code quality. Firefox tests Rust components thoroughly. DodaZIP uses unit and integration tests for file processing.
Real-World Use
CI/CD pipelines, regression prevention, documentation verification, API Contract Testing.
pub fn add(left: usize, right: usize) -> usize {
left + right
}
pub fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("division by zero"))
} else {
Ok(a / b)
}
}
/// Adds two numbers
/// ```
/// let result = mylib::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_divide_success() {
assert_eq!(divide(10.0, 2.0).unwrap(), 5.0);
}
#[test]
fn test_divide_by_zero() {
assert!(divide(10.0, 0.0).is_err());
}
#[test]
#[should_panic(expected = "index out of bounds")]
fn test_out_of_bounds() {
let v = vec![1, 2, 3];
v[99];
}
#[test]
fn test_with_result() -> Result<(), String> {
if divide(10.0, 2.0)? == 5.0 {
Ok(())
} else {
Err(String::from("wrong result"))
}
}
#[test]
#[ignore]
fn expensive_test() {
// ignored by default
}
}
# Run tests
cargo test
cargo test test_add
cargo test -- --ignored
cargo test --test integration_test
← Previous
Rust Collections — Vectors, Strings, HashMaps, and Collection Operations
Next →
Rust Crates — Publishing and Using Crates from crates.io and Private Registries
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro