Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ CONFIDENCE IN THE BUILD
BUILD NOTE 35 / 53

Turn an assumption into a check.

Write focused tests for normal cases and boundaries.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/unit-tests/src/main.rs
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));
}
↳ EXPECTED OUTPUT
0 100
  1. 1

    cfg(test) includes the test module only in a test build.

  2. 2

    cargo test or rustc --test runs the test harness.

  3. 3

    The ordinary binary still has its main function.

From the extracted rust-workbench folder
cargo run -p lesson_unit_tests

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write a median-of-three function and include repeated values in its tests.

Reveal one possible solution +
solutions/unit-tests/src/main.rs
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

QUICK SIGNAL CHECK

Which command runs Rust’s test harness?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.