Sub topic 12
Unit tests next to the code
This chapter assumes you can write basic Rust functions, structs, and Result handling, and that you can run cargo build. You should also know how modules nest and how use and pub work, covered in earlier chapters.
A unit test checks one small piece of code, usually a single function or type, in isolation. Rust lets you put unit tests in the same file as the code they test. This chapter covers how that works, why it works, and the mistakes people commonly make.
The working model
A Rust test is an ordinary function marked with the #[test] attribute. When you run cargo test, Cargo builds a special test binary. That binary contains a test harness, which finds every #[test] function, runs each one, and reports pass or fail. A test passes if the function returns normally. It fails if the function panics.
Unit tests conventionally live in a child module named tests at the bottom of the file under test. That module carries the #[cfg(test)] attribute.
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(())
}
#[test]
fn rejects_invalid_port() {
assert!(parse_port("abc").is_err());
}
#[test]
#[should_panic(expected = "index out of bounds")]
fn out_of_range_index_panics() {
let v = vec![1, 2, 3];
let _ = v[10];
}
}Three pieces make this work.
`#[cfg(test)]`
cfg is conditional compilation. #[cfg(test)] tells the compiler to include the module only when building for cargo test. In a normal cargo build the module is not compiled at all. Your test code adds nothing to the release binary, and it can use dev-dependencies that the normal build never sees.
`use super::*;`
The tests module is a separate module, so it does not see the parent's names automatically. use super::*; imports everything from the parent module into the test module. This includes private items.
That last point is the main reason to keep unit tests next to the code. Privacy in Rust works by module ancestry: a child module can see the private items of its ancestors. The tests module is a child of the module under test, so parse_port is visible even though it is not pub. You can test internal helpers without making them public.
`#[test]`
Each function marked #[test] is registered with the harness. A test function takes no arguments and returns either () or a Result<(), E> where E: Debug. The harness collects them from the whole crate, including nested modules, and gives each a name based on its module path, such as tests::adds_two_numbers.
Result-returning tests
A test can return Result<(), E>. This lets you use the ? operator instead of calling unwrap() on every fallible step. If the function returns Err, the test fails, and the harness prints the error using its Debug form.
In parses_valid_port above, parse_port("8080")? converts a parse failure into a failed test with a readable message. This is usually cleaner than .unwrap(), which panics with a less specific message.
One limit: you cannot combine #[should_panic] with a Result return type. To check that a function returns an error, assert on the result directly, as rejects_invalid_port does with is_err().
Assertion macros
The standard library provides three assertion macros. All of them panic on failure, which is what fails the test.
| Macro | Passes when | Notes |
|---|---|---|
| `assert!(cond)` | `cond` is `true` | Prints only the failed expression by default |
| `assert_eq!(left, right)` | `left == right` | Needs `PartialEq` and `Debug`. Prints both values |
| `assert_ne!(left, right)` | `left != right` | Same trait requirements |
Prefer assert_eq! over assert!(a == b). When it fails, it prints both values, so you see what went wrong without adding debug output.
Each macro accepts an optional custom message after the required arguments. The message uses the same syntax as format!.
fn double(n: i32) -> i32 {
n * 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn doubles_with_context() {
let input = 21;
assert_eq!(double(input), 42, "double({input}) returned the wrong value");
}
}The custom message appears only when the assertion fails.
Expected panics
Sometimes the correct behavior is to panic, for example when a function documents that it panics on invalid input. Mark such a test with #[should_panic]. The test passes if the function panics and fails if it returns normally.
A bare #[should_panic] passes on any panic, including one caused by an unrelated bug. Add expected = "..." to require that the panic message contains a given substring. In out_of_range_index_panics, the substring "index out of bounds" ensures the panic came from the indexing and not from something else.
What unit tests can and cannot see
Because the test module is a child of the code it tests, it sees everything in its ancestors. It does not see sibling modules' private items, though. If a and b are sibling modules, a test inside a::tests can use a's private items and b's public items, but not b's private ones.
Common errors
- Forgetting
#[cfg(test)]. The tests still compile and run undercargo test, but they are also built into normal builds. You get dead-code warnings and a larger binary, and test-only imports can fail to resolve. - Forgetting
use super::*;. The compiler reportscannot find functionfor items that exist in the parent. Thetestsmodule needs its own imports. - Using
assert_eq!on types withoutDebug. The macro needsDebugto print values on failure. Derive it with#[derive(Debug, PartialEq)]on your types. - Comparing floating-point numbers with
assert_eq!. Rounding error makes exact equality unreliable. Compare the absolute difference against a small tolerance instead. - Adding
#[should_panic]to a test that returnsResult. This is rejected. Remove the return type and let the test panic, or assert on theErrvalue. - Depending on test order or shared state. The harness runs tests in parallel on multiple threads, in no guaranteed order. A test that writes a file or changes a global that another test reads will fail unpredictably. Give each test its own data.
Helpers inside the test module
The tests module is normal Rust code, so you can define helper functions, constants, and builder functions inside it. Functions without #[test] are not run as tests, and they can be reused by several tests.
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn manhattan(a: &Point, b: &Point) -> i32 {
(a.x - b.x).abs() + (a.y - b.y).abs()
}
#[cfg(test)]
mod tests {
use super::*;
fn origin() -> Point {
Point { x: 0, y: 0 }
}
#[test]
fn distance_to_self_is_zero() {
assert_eq!(manhattan(&origin(), &origin()), 0);
}
#[test]
fn distance_is_symmetric() {
let p = Point { x: 3, y: 4 };
assert_eq!(manhattan(&origin(), &p), manhattan(&p, &origin()));
}
}Where unit tests belong
Use unit tests for logic you want to check in small pieces, especially internal functions and edge cases such as empty input, boundary values, and error paths. Use integration tests, covered later, to confirm that the public API works as an outside user would use it. Unit tests are fast because they run inside one binary with no extra linking, so they suit a tight edit-and-test loop.
Exercise
A file contains a private function fn clamp_percent(n: i32) -> i32 that returns n limited to the range 0 to 100. Describe where you would write a test for it, what attributes you need, and write a test that checks that 150 becomes 100.
Show answer
Put a mod tests at the bottom of the same file, marked #[cfg(test)], and add use super::*; so the private function is visible. For example:
#[cfg(test)]
mod tests {
use super::;
#[test]
fn clampshighvalues() {
asserteq!(clamppercent(150), 100);
}
}
The #[cfg(test)] attribute keeps the module out of normal builds. `use super::; works for a private function because a child module can see the private items of its parent. #[test]` registers the function with the harness.
Exercise
A test is marked #[should_panic] and also returns Result<(), String>. What happens, and what are two ways to fix it?
Show answer
The compiler rejects the combination, because a #[should_panic] test cannot return Result. One fix is to remove the return type and let the code panic. The other is to drop #[should_panic] and assert on the error directly, for example with assert!(result.is_err()) or by matching on the Err value.