By the end of this lesson
Run automated assertions for both success and failure.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 25, or be comfortable explaining and running its examples.
Three words to know
- Assertion
- A check that fails a test when a condition is false.
- Unit test
- A test of a small piece of behaviour.
- Boundary case
- An input at or near a documented limit.
1. Understand the idea
#[test] marks a test function. cargo test compiles and runs the test harness; a panic in an assertion means that test failed. Put tests near a small pure helper and check the contract rather than copying its implementation. Include invalid cases and boundaries, not only the example shown in a lesson. Passing tests are evidence about those cases, not a proof of every possible behaviour.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
fn valid_count(value: u32) -> bool { (1..=50).contains(&value) }
fn main() { println!("valid={}", valid_count(1)); }
#[cfg(test)]
mod tests {
use super::*;
#[test] fn accepts_edges() { assert!(valid_count(1)); assert!(valid_count(50)); }
#[test] fn rejects_outside() { assert!(!valid_count(0)); assert!(!valid_count(51)); }
}
What you should see · example output
valid=true
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
Compile normally to run main. To run the tests without Cargo, use rustc --edition=2024 --test lesson.rs -o lesson-tests and then ./lesson-tests (PowerShell: output lesson-tests.exe and run .\lesson-tests.exe). Inside a Cargo package, place the source in its binary file and use cargo test. Two test functions cover four boundary values.
YOUR TURN
A small check before you continue
Would checking only the input 25 establish that 0 and 51 are rejected?
Show a suggested answer
No. Add explicit tests for both sides of the valid interval.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
