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. }
  4. pub fn main() {
  5. println!("{}", helper("Hello", "World"));
  6. }
  7. #[cfg(test)]
  8. mod tests {
  9. use super::*;
  10. #[test]
  11. fn test_helper() {
  12. assert_eq!(helper("foo", "bar"), "foo bar");
  13. }
  14. }
  • This lets you unit test private helpers.
  • The #[cfg(test)] attribute is only active when you run cargo test.