Sub topic 12
Unit tests next to the code
This chapter assumes you know basic Rust syntax, how modules and use work, and how to run cargo build. Rust lets you put unit tests in the same file as the code they check. This chapter shows how that works and why it gives tests access to private items.
What a unit test is
A unit test checks one small piece of code, such as a single function, in isolation. In Rust, unit tests live in the same file as the code under test. By convention they go in a child module named tests at the bottom of the file.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn parses_valid_port() -> Result<(), std::num::ParseIntError> {
assert_eq!(parse_port("8080")?, 8080);
Ok(())
}
}Run it with cargo test. Cargo builds the crate in test mode, finds every function marked #[test], and runs each one.
The three pieces
#[test]marks a function as a test. A test passes if it returns normally and fails if it panics.#[cfg(test)]is a conditional compilation attribute. The module it marks is compiled only forcargo test. It adds nothing to your normal build, so test helpers cost you nothing in release binaries.use super::*;imports everything from the parent module into the test module.
Why tests can see private items
The tests module is a child of the module it tests. In Rust, a child module can use the private items of its ancestors. That is why parse_port, which is not pub, can be called from the test above.
This is a main reason to keep unit tests next to the code. You can check internal helpers directly, without widening their visibility just for testing.
Common errors
- Forgetting
use super::*;. The test module is a separate scope. Without the import, the compiler reports thataddcannot be found. - Omitting
#[cfg(test)]. The tests still run, but the module is compiled into normal builds. Helper imports can then trigger unused-code warnings. - Returning
Resultbut using?on a mismatched error type. The error type in the test's return type must accept the error you propagate. - Expecting a test to pass by printing. Output from passing tests is captured and hidden. Only failures show it.
Keeping tests focused
Give each test one behavior and a name that states it, like rejects_invalid_port. When a test fails, Cargo prints the test name. A clear name tells you what broke before you open the code.
Exercise
A function fn clamp_port(n: u32) -> u16 is private to its module. Where do you put a test for it, and what two lines make the test module able to call it?
Show answer
Put the test in a #[cfg(test)] mod tests block in the same file, as a child module. Inside it, use super::*; brings clamp_port into scope, and #[test] on the test function registers it. A child module can access its parent's private items, so clamp_port does not need to be pub.
Exercise
You run cargo test and a passing test's println! output does not appear. Is the test broken?
Show answer
No. Cargo captures output from passing tests and shows it only for failures. To see it for every test, run cargo test -- --nocapture.