Test. 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.
Example. We have a Rust program with 3 functions—the first 2 functions are decorated with the test macro. These are test functions.
Part 1 The multiply() test function ensures that the values 10 and 2, when multiplied together, equal 20.
Part 2 This test fails, as the assert_eq macro causes a panic to occur (10 multiplied by 2 is not 30).
Part 3 This is the main entry point—when "cargo run" is specified, this function executes (and no test functions do).
// 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.