Turn an assumption into a check.
Write focused tests for normal cases and boundaries.
01 Understand the contract
A function annotated with #[test] is discovered by the Rust test harness. Tests normally live in a cfg(test) module and can access private code in their parent module. assert_eq! shows both sides on failure; Result-returning tests can use ? for setup. Test behavior rather than the incidental implementation. Include empty input, boundary values, and failure cases that matter to the function’s contract. A passing example is useful evidence, but it cannot establish correctness for every possible input.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn clamp(n: i32) -> i32 {
n.clamp(0, 100)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn handles_edges() {
assert_eq!(clamp(-1), 0);
assert_eq!(clamp(101), 100);
}
#[test]
fn keeps_in_range() {
assert_eq!(clamp(50), 50);
}
}
fn main() {
println!("{} {}", clamp(-5), clamp(120));
}0 100
- 1
cfg(test) includes the test module only in a test build.
- 2
cargo test or rustc --test runs the test harness.
- 3
The ordinary binary still has its main function.
cargo run -p lesson_unit_tests03 Mind the boundary
04 Your next build
Write a median-of-three function and include repeated values in its tests.
Reveal one possible solution +
fn median(a: i32, b: i32, c: i32) -> i32 {
let mut v = [a, b, c];
v.sort();
v[1]
}
#[test]
fn orders() {
assert_eq!(median(8, 1, 3), 3);
assert_eq!(median(2, 2, 9), 2);
}
fn main() {
assert_eq!(median(9, 3, 1), 3);
}05 Check your reasoning
Which command runs Rust’s test harness?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.