If code does not work correctly, it is a problem that can cause all sorts of errors. With the test macro in Rust, we can run tests to ensure our code works correctly.
With this macro, we specify that a function is a test method. Then when the program is evaluated with "cargo test," the tests are executed and cargo ensures no panics occur.
We have a Rust program with 3 functions—the first 2 functions are decorated with the test macro. These are test functions.
multiply()
test function ensures that the values 10 and 2, when multiplied together, equal 20.assert_eq
macro causes a panic to occur (10 multiplied by 2 is not 30).// Part 1: use test macro with assert_eq check for panics. #[test] fn multiply() { let x = 10; if let Ok(y) = "2".parse::<usize>() { let result = x * y; assert_eq!(result, 20); } } // Part 2: this test fails as assert_eq! panics. #[test] fn fail() { let x = 10; if let Ok(y) = "2".parse::<usize>() { let result = x * y; assert_eq!(result, 30); } } fn main() { // Part 3: if executed normally, this message is printed, and no tests run. println!("Done"); }' % cargo test running 2 tests test multiply ... ok test fail ... FAILED failures: ---- fail stdout ---- thread 'fail' panicked at src/main.rs:17:9: assertion `left == right` failed left: 20 right: 30' % cargo run Done
Ensuring code quality is paramount in Rust programs (as it is in programs from all other languages). With the built-in test macro we can add command-line tests to ensure our logic remains correct.