Stage 2.10: How to test functions
Rust provides a built-in testing tool with cargo test
Since you don't want testing code being a part of your production program, you have to tell the
Rust compiler that it's for testing only.
You can do that by annotating #[cfg(test)]
. Rust will compile all code after it
only if you run cargo test
.
After this annotation, we will create an own module (container) for our test with mod test { }
.
Since functions are block-scoped, we have to tell our module, to import everthing from the outer
module with use super::*;
Now we are good to go and can write actual test functions. Since there can be setup functions or
utility functions, you have to tell cargo test
which function should be tested by
annotating it with #[test]
Finally we have 3 assert macros to actually test a function. To test if something is equal (assert_eq!
), not equal (assert_ne!
) or if something is simply true
(assert!
).
You will learn all those new things in detail in later lessons. Don't worry.
Further information: