intermediateTesting
Unit Tests
Write unit tests with #[test] attribute.
Unit Tests
Write unit tests with #[test] attribute.
Difficulty
Intermediate
Code
rust
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_add_negative() {
assert_eq!(add(-1, 1), 0);
}
#[test]
#[should_panic]
fn test_panic() {
panic!("expected panic");
}
}
fn main() {
println!("Run with: cargo test");
}Explanation
This example demonstrates how to use unit tests in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the testing category to build a complete understanding of this topic.