Test Modules

Unit tests are often put in a nested module (run tests on the Playground):

1. fn helper(a: &str, b: &str) -> String {
2. format!("{a} {b}")
3. }

5. pub fn main() {
6. println!("{}", helper("Hello", "World"));
7. }

9. #[cfg(test)]
10. mod tests {
11. use super::*;

13. #[test]
14. fn test_helper() {
15. assert_eq!(helper("foo", "bar"), "foo bar");
16. }
17. }
  • This lets you unit test private helpers.
  • The #[cfg(test)] attribute is only active when you run cargo test.