Unit Tests

Rust and Cargo come with a simple unit test framework:

  • Unit tests are supported throughout your code.

  • Integration tests are supported via the tests/ directory.

Tests are marked with #[test]. Unit tests are often put in a nested tests module, using #[cfg(test)] to conditionally compile them only when building tests.

  1. fn first_word(text: &str) -> &str {
  2. match text.find(' ') {
  3. Some(idx) => &text[..idx],
  4. None => &text,
  5. }
  6. }
  7. #[cfg(test)]
  8. mod tests {
  9. use super::*;
  10. #[test]
  11. fn test_empty() {
  12. assert_eq!(first_word(""), "");
  13. }
  14. #[test]
  15. fn test_single_word() {
  16. assert_eq!(first_word("Hello"), "Hello");
  17. }
  18. #[test]
  19. fn test_multiple_words() {
  20. assert_eq!(first_word("Hello World"), "Hello");
  21. }
  22. }
  • This lets you unit test private helpers.
  • The #[cfg(test)] attribute is only active when you run cargo test.

This slide should take about 5 minutes.

Run the tests in the playground in order to show their results.