typestar

Unit tests in Rust

Tests live beside the code in a cfg(test) module, compiled only for test runs.

fn slugify(title: &str) -> String {
    title
        .to_lowercase()
        .split_whitespace()
        .collect::<Vec<&str>>()
        .join("-")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn joins_words_with_hyphens() {
        assert_eq!(slugify("Language Basics"), "language-basics");
    }

    #[test]
    fn collapses_extra_spaces() {
        assert_eq!(slugify("  Two   Words "), "two-words");
        assert!(!slugify("A B").contains(' '));
    }
}

fn main() {
    println!("{}", slugify("Traits And Generics"));
}

How it works

  1. #[cfg(test)] keeps the module out of release builds.
  2. use super::* pulls the code under test into scope.
  3. assert_eq! prints both sides when it fails.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
454
Tokens
136
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 1 of 3 in Tests & docs, step 4 of 12 in Modules, tests & macros.

← Previous Next →