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. }

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

12. #[test]
13. fn test_empty() {
14. assert_eq!(first_word(""), "");
15. }

17. #[test]
18. fn test_single_word() {
19. assert_eq!(first_word("Hello"), "Hello");
20. }

22. #[test]
23. fn test_multiple_words() {
24. assert_eq!(first_word("Hello World"), "Hello");
25. }
26. }
  • 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.