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
#[cfg(test)]keeps the module out of release builds.use super::*pulls the code under test into scope.assert_eq!prints both sides when it fails.
Keywords and builtins used here
StringVeccollapses_extra_spacesfnjoins_words_with_hyphensmainmodslugifystrsuperuse
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.
Step 1 of 3 in Tests & docs, step 4 of 12 in Modules, tests & macros.