Practical Rust
Assertions
Checking a Function
Assertions verify expected results. Real test functions use #[test] with cargo test; this example checks inline with assert_eq!.
Program
Play the program to verify a double function and confirm all checks pass.
unit_tests.rs
Replay: real traced execution (multi-file project)
fn double(n: i32) -> i32 {
n * 2
}
fn main() {
assert_eq!(double(2), 4);
assert_eq!(double(0), 0);
println!("all checks passed");
}
fn double(n: i32) -> i32
pass 1 of 21fn double(n: i32) -> i32 {2 2n * 23}assert_eq!(double(2), 4);
5fn main() {6 assert_eq!(double(2), 4);7 assert_eq!(double(0), 0);8 println!("all checks passed");fn double(n: i32) -> i32
pass 2 of 21fn double(n: i32) -> i32 {2 0n * 23}assert_eq!(double(0), 0);
6 assert_eq!(double(2), 4);7 assert_eq!(double(0), 0);8 println!("all checks passed");9}outputall checks passed
assert_eq!
`assert_eq!(a, b)` panics if the values differ.
function under test
`double` is the code being checked.
cargo test
Real tests live in `#[test]` functions run by `cargo test`.