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.

fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(idx) => &text[..idx],
        None => &text,

mod tests {
    use super::*;

    fn test_empty() {
        assert_eq!(first_word(""), "");

    fn test_single_word() {
        assert_eq!(first_word("Hello"), "Hello");

    fn test_multiple_words() {
        assert_eq!(first_word("Hello World"), "Hello");
  • 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.