intermediateTesting
Test Organization
Organize tests with modules and helper functions.
Test Organization
Organize tests with modules and helper functions.
Difficulty
Intermediate
Code
rust
pub fn add(a: i32, b: i32) -> i32 { a + b }
pub fn mul(a: i32, b: i32) -> i32 { a * b }
#[cfg(test)]
mod tests {
use super::*;
// helper function for tests
fn assert_add(a: i32, b: i32, expected: i32) {
assert_eq!(add(a, b), expected, "add({}, {}) should be {}", a, b, expected);
}
mod add_tests {
use super::*;
#[test]
fn positive() { assert_add(2, 3, 5); }
#[test]
fn negative() { assert_add(-1, -2, -3); }
#[test]
fn zero() { assert_add(0, 0, 0); }
}
mod mul_tests {
use super::*;
#[test]
fn basic() { assert_eq!(mul(3, 4), 12); }
#[test]
fn identity() { assert_eq!(mul(5, 1), 5); }
}
}
fn main() {
println!("Run with: cargo test");
}Explanation
Organize tests with nested modules and helpers.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the testing category to build a complete understanding of this topic.