Answer#
No test framework is needed: a function marked #[test] is a test, and it passes unless it panics. cargo test builds the crate in test mode, runs every kind of test, and prints one result block per kind.
How to do it#
- Unit tests go in the same file as the code, in a module that is only compiled for tests. They can use private functions.
- Integration tests go in
tests/*.rs. Each file is its own crate and sees only what your library makespub. - Doc tests are the code blocks in
///comments. They are compiled and run too, so examples in the documentation cannot go stale.
/// Returns the larger of two numbers.
///
/// ```
/// assert_eq!(tst::larger(2, 9), 9);
/// ```
pub fn larger(a: i32, b: i32) -> i32 {
if a > b { a } else { b }
}
pub fn parse_age(text: &str) -> Result<u8, String> {
text.trim().parse::<u8>().map_err(|e| format!("not an age: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_picks_the_bigger_number() {
assert_eq!(larger(3, 1), 3);
assert_eq!(larger(-5, -2), -2);
}
#[test]
fn parse_age_accepts_spaces() {
assert_eq!(parse_age(" 42 "), Ok(42));
}
#[test]
fn parse_age_rejects_text() {
assert!(parse_age("old").is_err());
}
#[test]
#[should_panic(expected = "attempt to divide by zero")]
fn division_by_zero_panics() {
let zero = std::env::args().count() as i32 - 1;
let _ = 1 / zero;
}
}// Integration tests live in tests/ and use the crate only through its public API.
#[test]
fn public_api_works_together() {
let age = tst::parse_age("30").unwrap();
assert_eq!(tst::larger(age as i32, 18), 30);
}- Run them.
> cargo test
Running unittests src\lib.rs
running 4 tests
test tests::parse_age_accepts_spaces ... ok
test tests::larger_picks_the_bigger_number ... ok
test tests::parse_age_rejects_text ... ok
test tests::division_by_zero_panics - should panic ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
Running tests\api.rs
running 1 test
test public_api_works_together ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
Doc-tests tst
running 1 test
test src\lib.rs - larger (line 3) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
all doctests ran in 0.71s; merged doctests compilation took 0.54sWhy it works#
#[cfg(test)] removes the test module from normal builds, so tests add nothing to your program. assert_eq! panics with both values printed when they differ, and the test harness reports a panicking test as failed. #[should_panic(expected = "...")] turns it around: the test passes only if the panic message contains the text.
Common mistakes#
- Testing a result by printing it. Print output is hidden for passing tests; use
assert!andassert_eq!. - Expecting tests to run in order. They run in parallel threads, so tests must not share files or global state. Run one at a time with
cargo test -- --test-threads=1if they do. - Writing a doc test for code that is not
pub: doc tests see the crate like an outside user does.
Related questions#
How do I run only some tests?#
Pass part of a name: cargo test parse_age runs every test whose path contains it.
How do I see the output of a passing test?#
cargo test -- --nocapture.
In Ruststudio#
Run > Test: Run All Tests (Ctrl+Shift+T) runs the tests, Run > Test: Run Test at Cursor (F6) runs the one under the cursor, and the Test Explorer (Alt+F6) lists them. The menu also offers a run with cargo nextest and a run with coverage; those need the extra tool installed.