Assertions and table-driven tests
Quick answer
Assertions describe conditions that must hold. Table-driven tests apply the same check to multiple input and expected-output pairs.
Choose useful cases
Use assert! for Boolean conditions, assert_eq! for equality and assert_ne! for inequality. Unlike debug_assert!, ordinary assertions remain active in optimized builds. For numerical functions, choose normal, boundary and invalid inputs according to their contract.
fn cap(x: u32) -> u32 { x.min(10) }fn main() { for (input, expected) in [(0, 0), (10, 10), (11, 10)] { assert_eq!(cap(input), expected, "input={input}"); } println!("3 cases passed");}Expected stdout (not executed):
3 cases passedThe message identifies the input if the assertion fails.
fn main() { assert!("abc".parse::<u32>().is_err()); assert_ne!("5".parse::<u32>().unwrap(), 0); println!("ok");}Expected stdout (not executed):
okCheck failure as well as successful conversion.
Common mistake
Do not put required side effects in debug_assert!.
Try it yourself
Add a maximum-value case using u32::MAX for cap.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Assertions and table-driven tests — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A function accepts values 1 through 10. Which test set best checks boundaries?
Assertions and table-driven tests — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn cap(x: u32) -> u32 { x.min(10) } fn main() { for (input, expected) in [(0, 0), (10, 10), (11, 10)] { assert_eq!(cap(input), expected, "input={input}"); } println!("3 cases passed"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Assertions and table-driven tests — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { assert!("abc".parse::<u32>().is_err()); assert_ne!("5".parse::<u32>().unwrap(), 0); println!("ok"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.