We can prefix a function with the #[test]
attribute to indicate that it is part of the unit tests for our application or library. We can then compile with rustc --test program.rs
. This will replace the main()
function with a test runner and show the result from the functions marked with #[test]
. Have a look at the following code snippet:
// from Chapter 3/code/attributes_testing.rs fn main() { println!("No tests are compiled,compile with rustc --test! "); } #[test] fn arithmetic() { if 2 + 3 == 5 { println!("You can calculate!"); } }
Test functions, such as arithmetic()
in the example, are black boxes; they have no arguments or returns. When this program is run on the command line, it produces the following output:
However, even if we change the test to if 2 + 3 == 6
, the test passes! Try it out. It turns out that test functions always pass when their execution does not cause a crash (called a panic in Rust terminology), and it fails when it does panic. This is why testing...