Testing
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 then compile with the following command and run the generated executable:
rustc --test program.rs
This will replace the main()
function with a test runner, and show the result from the functions marked with #[test]
, for example:
// 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, like 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:

But, if we change the test to if 2 + 3 == 6
the test passes as well! 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 only fails when it panics...