Rust Unit Tests
Run real tests in addition to printing a successful example.
How it works
Rust’s test harness compiles functions marked with test and reports their assertions. Keep tests close to a public contract and include invalid input or boundary cases, not only the first successful example. A binary printing that tests passed would not itself be a test run. The course reviewer compiles this exact source with rustc --test and executes the harness separately.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
pub fn packets(trays: u32) -> Option<u32> { trays.checked_mul(3) }
#[cfg(test)]
mod tests {
use super::packets;
#[test] fn ordinary() { assert_eq!(packets(4), Some(12)); }
#[test] fn zero() { assert_eq!(packets(0), Some(0)); }
#[test] fn overflow() { assert_eq!(packets(u32::MAX), None); }
}
fn main() { assert_eq!(packets(4),Some(12)); println!("Example gives 12; run rustc --test to execute three tests"); }
Expected result
Example gives 12; run rustc --test to execute three tests
The normal binary checks one demonstration, while the separate harness runs ordinary, zero and overflow tests. After saving testing.rs, use rustc --edition=2024 --test testing.rs -o testing-tests and run the resulting executable; on Windows it has an .exe suffix. Cargo test provides the same workflow for a package.
Primary technical reference: Rust documentation.