In Rust, how does a unit test returning `Result<(), E>` use `?`, and what does the harness print when it returns `Err`?
answer
- the return type is a trait bound
- Termination and its report method
- the error's Debug form, no location
- incompatible with one testing attribute
basics
~10 sA test returning Result<(), E> with E: Debug can use ?; Ok(()) passes and Err fails, printing Error: and the error's Debug form without a line number. It cannot carry #[should_panic].
solid answer
~40 sA `#[test]` function may return any `Termination` type, and `Result<(), E>` with `E: Debug` is the usual one: `?` returns early with the `Err`, so `charge_cents("125")?` replaces an `unwrap()`. The harness counts `Ok(())` as a pass and `Err` as a failure, printing `Error: ` and the error's `Debug` form, such as `Error: ParseIntError { kind: InvalidDigit }`, with no file or line, unlike a panic from `unwrap` or `expect`. An error type without `Debug` is rejected with E0277, and `Box<dyn std::error::Error>` lets one test mix error types. Such a test cannot carry `#[should_panic]`, and it must not apply `?` to the call whose failure it is checking: assert on the `Result` instead, for example with `assert!(r.is_err())`.
code
rust · 40 linesuse std::num::ParseIntError;
/// Parses an amount in tenths of a cent, such as "125", and rounds it to cents.
pub fn charge_cents(input: &str) -> Result<i64, ParseIntError> {
let tenths: i64 = input.trim().parse()?;
Ok(round_half_even(tenths))
}
fn round_half_even(tenths: i64) -> i64 {
let (q, r) = (tenths.div_euclid(10), tenths.rem_euclid(10));
match r {
0..5 => q,
5 if q % 2 == 0 => q,
_ => q + 1,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn charges_round_half_even() -> Result<(), ParseIntError> {
assert_eq!(charge_cents("125")?, 12);
assert_eq!(charge_cents(" 135 ")?, 14);
Ok(())
}
// Wrong: `?` turns the expected failure into a failing test.
#[test]
fn decimal_point_rejected_wrong() -> Result<(), ParseIntError> {
charge_cents("12.5")?;
Ok(())
}
#[test]
fn decimal_point_rejected() {
assert!(charge_cents("12.5").is_err());
}
}go deeper
Recall that a test can return Result<(), E> and use ?, and that returning Err fails the test.
Explain Termination: the harness calls report, Ok(()) passes, Err prints Error: with the Debug form, E must be Debug, and should_panic needs a () return.
Weigh ? against expect in tests by the diagnostics each leaves behind, and spot the test that applies ? to the very failure it means to check.
Agree one convention for fallible setup in tests so that failures across the suite read the same way and point at the step that broke.
## Why a test returns `Result` Tests in a currency module often call fallible functions. `charge_cents("125")` parses an amount in tenths of a cent and returns `Result<i64, ParseIntError>`. A test returning `()` has to `unwrap()` every call. A test declared `-> Result<(), ParseIntError>` can use the **`?` operator** instead: ```rust #[test] fn charges_round_half_even() -> Result<(), ParseIntError> { assert_eq!(charge_cents("125")?, 12); assert_eq!(charge_cents(" 135 ")?, 14); Ok(()) } ``` `?` works here for the same reason it works in any function returning `Result`: on `Err` it converts the error with `From` and returns it early. ## How the harness decides The Reference requires a `#[test]` function's return type to implement the **`Termination`** trait. The harness calls the returned value's `report` method and treats a successful exit code as a pass: | Return type | Passes when | |---|---| | `()` | the function returns without panicking | | `Result<(), E>` with `E: Debug` | it returns `Ok(())` | | `std::process::ExitCode` | it returns `ExitCode::SUCCESS` | It is the same trait that lets `main` return a `Result`, applied per test. ## What a failing `Result` test prints When the test returns `Err`, the `Termination` impl writes `Error: ` and the error's `Debug` form, and the test is marked failed: ```plaintext ---- tests::decimal_point_rejected_wrong stdout ---- Error: ParseIntError { kind: InvalidDigit } ``` Note what is **missing**: no file, no line, no indication of which `?` returned. A panic from `unwrap()` or `expect()` reports `panicked at src/lib.rs:LINE:COLUMN`. In a test with five `?` calls that return the same error type, the `Debug` output may be all you get. ## Mixing error types with `Box<dyn Error>` A test often touches more than one fallible API. Declaring the error type as `Box<dyn std::error::Error>` lets every `?` convert its own error into the box, because the standard library provides `From<E> for Box<dyn Error>` for any `E: Error`: ```rust #[test] fn rate_and_amount_parse() -> Result<(), Box<dyn std::error::Error>> { let rate: f64 = "1.25".parse()?; // ParseFloatError let cents = charge_cents("125")?; // ParseIntError assert_eq!((cents as f64 * rate).round(), 15.0); Ok(()) } ``` When such a test fails, the box's `Debug` output is the inner error's, so the report still reads `Error: ParseIntError { kind: InvalidDigit }`, and it still carries no location. ## Rules and limits - **`E` must implement `Debug`.** With an error type that lacks it, rustc rejects the signature with E0277, "doesn't implement `Debug`". - **Mixed error types** need a common type: `Result<(), Box<dyn std::error::Error>>` accepts any error that converts into it, so `?` works on parse errors and I/O errors in one test. - **No `#[should_panic]`.** rustc rejects the combination with "functions using `#[should_panic]` must return `()`". A test that expects a panic returns `()`. - **`?` on the call under test is a trap.** If the test exists to check that `charge_cents("12.5")` fails, `charge_cents("12.5")?` makes the expected error fail the test. ## Testing the error path To check that a call fails, keep the `Result` and assert on it: 1. `assert!(charge_cents("12.5").is_err());` for a plain yes-or-no check. 2. `assert!(matches!(charge_cents("12.5"), Err(_)));` when you need a pattern. 3. `let err = charge_cents("12.5").unwrap_err();` followed by assertions on `err`, when the error's contents matter. `unwrap_err` panics if the call unexpectedly succeeds, and it needs the success type to implement `Debug` so it can print it. These run in a test returning `()` or `Result`; the `?` operator is only for calls that are expected to succeed. ## Choosing between `?` and `unwrap` in tests - Use **`?`** when the setup is fallible and noise matters more than location: fixtures, parsing test data, file I/O in a temporary directory. - Use **`expect("...")`** when knowing which step failed matters; its message and the panic location do the work that `Error: ...` cannot. - Keep **one style per test module**, so a reader knows whether a failure will come with a location. - Remember that an `assert_eq!` inside a `Result` test still panics on a mismatch, with its usual location and values; only the `?` exits are location-free.
- Why might a reviewer ask for `expect("...")` instead of `?` in a particular test?A panic from `expect` reports its message and the file, line and column where it happened. A `Result` test that returns `Err` prints only `Error: ` and the error's `Debug` form, so with several `?` calls returning the same error type you cannot tell which step failed.
- Which return types besides `()` and `Result` can a `#[test]` function have?Any type implementing `Termination`; the Reference cites `std::process::ExitCode`, where `ExitCode::SUCCESS` passes and `ExitCode::FAILURE` fails. In practice `()` and `Result<(), E>` cover almost every unit test.
- A test returning Err is reported as passed, because ? handled the error.
- The harness prints the file and line of the ? that returned the error.
- Any error type works as E, even one without Debug.
- #[should_panic] and a Result return type can be combined to test errors.
- Applying ? to the call under test is the way to assert that it fails.