Sub topic 13
Assertions, expected panics, and Result tests
This chapter assumes you can write a basic #[test] function inside a #[cfg(test)] module and run cargo test. It covers how a test passes or fails, and three ways to express what you expect.
How a test fails
A test function passes if it returns normally. It fails if it panics. Every assertion macro is a conditional panic, so a failed assertion fails the test. Each test runs in its own thread, so one panic does not stop the others.
The assertion macros
Rust gives you three main macros.
| Macro | Passes when | Typical use |
|---|---|---|
| `assert!(cond)` | `cond` is `true` | Boolean checks, `is_err()`, `matches!` |
| `assert_eq!(left, right)` | `left == right` | Comparing values |
| `assert_ne!(left, right)` | `left != right` | Values that must differ |
assert_eq! and assert_ne! print both values when they fail. Both types must implement PartialEq and Debug. If you derive these traits on your own types, you can compare them directly.
Each macro accepts an optional message, using the same syntax as format!. Add one when the failure alone would not tell you what went wrong.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5, "2 + 3 should be 5");
}
#[test]
fn zero_is_neutral() {
assert_ne!(add(0, 7), 0);
assert!(add(0, 0) == 0, "zero plus zero was {}", add(0, 0));
}
}By convention, put the actual value on the left and the expected value on the right. The failure output labels them "left" and "right", so a consistent order makes it easier to read.
Expecting a panic
Some functions are supposed to panic, for example on an out-of-range index. Add #[should_panic] to assert that. The test passes only if the body panics.
#[cfg(test)]
mod tests {
#[test]
#[should_panic(expected = "index out of bounds")]
fn out_of_range_index_panics() {
let v = vec![1, 2, 3];
let _ = v[10];
}
}The expected string must appear as a substring of the panic message. Without it, any panic satisfies the test, including one caused by an unrelated bug. Always include expected so the test cannot pass for the wrong reason.
Tests that return Result
A test can return Result<(), E>, where E implements Debug. Returning Ok(()) passes. Returning Err fails, and the error is printed. This lets you use the ? operator instead of calling unwrap.
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[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());
}
}To check that a function returns an error, use assert!(result.is_err()) as above. Do not put #[should_panic] on a Result-returning test. Rust does not allow that combination.
Common errors
- Comparing types that lack
DebugorPartialEq. The compiler asks you to derive them. - Using
should_panicwithoutexpected, which hides unrelated panics. - Comparing floating-point numbers with
assert_eq!. Rounding can make equal-looking values differ, so check that the difference is within a small tolerance. - Forgetting that
?in a test needs aResultreturn type.
Exercise
A function halve(n: u32) -> u32 panics with the message "odd number" when n is odd. Write a test that passes only for that specific panic.
Show answer
Use #[test] with #[should_panic(expected = "odd number")] and a body that calls halve(3). The expected text stops the test from passing on an unrelated panic.
Exercise
Why might assert_eq!(0.1 + 0.2, 0.3) fail, and what should you write instead?
Show answer
Floating-point arithmetic rounds, so the sum is not exactly 0.3. Write assert!(((0.1_f64 + 0.2) - 0.3).abs() < 1e-9) to allow a small tolerance.