Sub topic 13
Assertions, expected panics, and Result tests
This chapter assumes you can write a #[test] function inside a #[cfg(test)] module and run cargo test, as covered in the previous chapter on unit tests. It also assumes you know Result, the ? operator, and the Debug and PartialEq traits at an introductory level.
A test passes if the function returns normally. It fails if the function panics. Everything in this chapter follows from that rule. Assertion macros panic when a condition is false. #[should_panic] flips the expectation. A test that returns Result fails when it returns Err.
How a test passes or fails
The test harness runs each #[test] function on its own thread and catches panics. A test passes when:
- the function returns
(), or - the function returns
Ok(())from aResult<(), E>.
A test fails when the function panics or returns Err. Because each test has its own thread, one failing test does not stop the others.
The assertion macros
Rust provides three main assertion macros, and all are available in test and non-test code.
| Macro | Passes when | Requires |
|---|---|---|
| `assert!(cond)` | `cond` is `true` | a `bool` expression |
| `assert_eq!(left, right)` | `left == right` | `PartialEq` and `Debug` on both types |
| `assert_ne!(left, right)` | `left != right` | `PartialEq` and `Debug` on both types |
Use assert_eq! and assert_ne! when you compare two values. On failure they print both values with {:?}, which is why both types must implement Debug. assert!(a == b) only tells you the condition was false.
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn origin() -> Point {
Point { x: 0, y: 0 }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn origin_is_zero() {
assert_eq!(origin(), Point { x: 0, y: 0 });
}
#[test]
fn origin_is_not_one_one() {
assert_ne!(origin(), Point { x: 1, y: 1 });
}
#[test]
fn x_is_not_negative() {
assert!(origin().x >= 0);
}
}If you remove #[derive(Debug, PartialEq)], assert_eq! no longer compiles. The compiler error names the missing trait.
Custom failure messages
Every assertion macro accepts extra arguments after the required ones. These are passed to format! and appear in the failure output.
fn double(n: i32) -> i32 {
n * 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn doubles_each_input() {
for n in 0..5 {
assert_eq!(double(n), n + n, "double({n}) gave the wrong result");
}
}
}A message matters most inside loops or helper functions. The default output shows the two values but not which iteration produced them.
Argument order
Rust does not distinguish "expected" from "actual". The failure output labels the values left and right. Pick one convention, such as actual on the left and expected on the right, and keep it across the project so failure output is easy to read.
Comparing floating-point numbers
Floating-point arithmetic is inexact, so assert_eq!(0.1 + 0.2, 0.3) fails. Compare with a tolerance instead.
#[cfg(test)]
mod tests {
#[test]
fn float_sum_is_close() {
let sum = 0.1_f64 + 0.2_f64;
assert!((sum - 0.3).abs() < 1e-9, "sum was {sum}");
}
}Debug-only assertions
debug_assert!, debug_assert_eq!, and debug_assert_ne! behave like their counterparts in debug builds and compile to nothing in release builds. Use them in library code to check internal invariants without a runtime cost in release. Tests normally run in the debug profile, so these macros are active under cargo test. They are not a substitute for real tests.
Testing for panics with should_panic
Some functions are meant to panic, for example on an out-of-range index or a violated precondition. Mark a test with #[should_panic] to pass only when the function panics.
pub fn percent(part: u32, whole: u32) -> u32 {
if whole == 0 {
panic!("whole must not be zero");
}
part * 100 / whole
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn zero_whole_panics() {
percent(1, 0);
}
}This test is loose. It passes for any panic, including one caused by a bug elsewhere in the function. Add an expected string to narrow it.
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "whole must not be zero")]
fn zero_whole_panics_with_message() {
percent(1, 0);
}
}The test passes only if the panic message contains the expected text. It is a substring match, not an exact match. A test that expects "zero" would also pass for a message such as "cannot divide by zero".
Limits of should_panic
- It checks only that a panic happened and, optionally, a substring of its message. It cannot check the panic's location or payload type.
- It works only for panics that unwind. If you set
panic = "abort"in the test profile, a panic ends the process and the harness cannot catch it. - You cannot combine
#[should_panic]with a test that returnsResult. The compiler rejects the combination. - Keep the panicking call as the only risky step in the test. Setup code that can also panic makes the test pass for the wrong reason.
For code that returns errors instead of panicking, do not use should_panic. Test the Err value directly, as the next section shows.
Tests that return Result
A test function may return Result<(), E>, where E implements Debug. Returning Err fails the test, and the harness prints the error with {:?}. This lets you use ? instead of calling unwrap() repeatedly.
use std::num::ParseIntError;
pub fn parse_pair(s: &str) -> Result<(i32, i32), ParseIntError> {
let (a, b) = s.split_once(',').unwrap_or((s, "0"));
Ok((a.trim().parse()?, b.trim().parse()?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_two_numbers() -> Result<(), ParseIntError> {
let (a, b) = parse_pair("3, 4")?;
assert_eq!((a, b), (3, 4));
Ok(())
}
#[test]
fn rejects_text() {
assert!(parse_pair("x,1").is_err());
}
}Two things to remember:
- The test must end with
Ok(()). Forgetting it is a type error, not a silent pass. - A
?that triggers makes the test fail with the error'sDebugoutput. This is useful when the error is not what you meant to test.
Mixed error types
If the test calls functions with different error types, use Box<dyn std::error::Error> as the error type. The ? operator converts each error into it.
use std::error::Error;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mixed_errors() -> Result<(), Box<dyn Error>> {
let n: i32 = "42".parse()?;
let text = std::str::from_utf8(&[104, 105])?;
assert_eq!(n, 42);
assert_eq!(text, "hi");
Ok(())
}
}Asserting that an error occurred
To check that a function fails in a specific way, match on the result instead of using should_panic. This is more precise, because you can compare the error value.
#[derive(Debug, PartialEq)]
pub enum ConfigError {
Empty,
TooLong(usize),
}
pub fn check_name(name: &str) -> Result<(), ConfigError> {
if name.is_empty() {
Err(ConfigError::Empty)
} else if name.len() > 8 {
Err(ConfigError::TooLong(name.len()))
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_name_is_rejected() {
assert_eq!(check_name(""), Err(ConfigError::Empty));
}
#[test]
fn long_name_reports_length() {
assert_eq!(check_name("abcdefghij"), Err(ConfigError::TooLong(10)));
}
}The ConfigError type derives Debug and PartialEq, so the whole Result can be compared in one assert_eq!. If your error type cannot implement PartialEq, as is common with std::io::Error, use matches! instead: assert!(matches!(result, Err(ConfigError::Empty))).
Choosing a style
| Situation | Preferred tool |
|---|---|
| Compare two values | `assert_eq!` |
| Check a boolean property | `assert!` with a message |
| Function must panic on bad input | `#[should_panic(expected = "...")]` |
| Function returns an error you want to inspect | `assert_eq!` on the `Result`, or `matches!` |
| Setup uses several fallible calls | Test returning `Result<(), E>` |
Common mistakes
- Using
unwrap()on a value that the test is meant to check. If it panics, the failure message shows only the unwrap location, not the intent. Preferassert_eq!on theResult. - Writing
#[should_panic]withoutexpected, as described above. - Putting several unrelated assertions in one test. The first failure stops the test, so later assertions never run. Split them into separate tests.
- Comparing floating-point values with
assert_eq!. - Forgetting
Debugon a type used inassert_eq!.
Exercise
A test is written as #[test] #[should_panic] fn t() { let v: Vec<i32> = Vec::new(); let n: i32 = "x".parse().unwrap(); let _ = v[0]; }. The author meant to test the out-of-range index. Why does this test give false confidence, and how would you fix it?
Show answer
The parse().unwrap() call panics first, so the test passes without ever reaching v[0]. Plain #[should_panic] accepts any panic. Fix it in two steps: remove the unrelated parse from the test so the index is the only panicking step, and add expected = "index out of bounds" so only the intended panic passes.
Exercise
Write a test for check_name from this chapter that returns Result<(), ConfigError> and uses ? to confirm that the name "ok" is accepted. What must the test return on its last line, and what does the harness do if check_name("ok") returned Err instead?
Show answer
#[test] fn short_name_is_ok() -> Result<(), ConfigError> { check_name("ok")?; Ok(()) }. The last line must be Ok(()). If check_name returned Err, the ? would return that error from the test, and the harness would mark the test failed and print the error with its Debug format. This requires ConfigError to implement Debug, which it does.