`#[test]`
#[test] marks a function as a unit test. cargo test builds a test harness and runs every such function, failing the run if any panics.
Detailed Explanation
#[test] fn parses_port() { assert_eq!(parse("8080"), Ok(8080)); } is a complete Rust unit test. The function takes no arguments and returns () or Result<(), E>. A panic fails the test. An Ok(()) or a quiet return passes. An Err from a Result-returning test also fails, which is why #[test] fn f() -> Result<(), Box<dyn Error>> plus ? is a pleasant style.
Unit tests live in the same crate, often in a #[cfg(test)] mod tests at the bottom of the file. That module can see private items. That is the point of a unit test: you exercise parse_inner without making it pub. Integration tests in tests/ cannot.
#[test] is an attribute the test harness looks for. It is not a runtime registration. Tests that do not compile are not skipped; the test crate fails to build. #[ignore] skips a test unless you pass --ignored. #[should_panic] inverts the outcome. Tokio's #[tokio::test] is a wrapper that starts a runtime so the test function can be async.
Tests run in parallel by default, one thread per test, unless you set --test-threads=1 or a file-level serial crate. Shared mutable statics and leftover temp files will flake. Isolate state.
When you write #[test]: a function, a module, an invariant. When you write an integration test: the public API of the crate as a client sees it. When you write a doc test: the snippet in the docs should compile and run.
Name tests after the behaviour, not the function: rejects_empty_token, not test_new. The filter string in cargo test rejects_ should mean something. A test that only proves the type checks is a compile-time job; delete it. A test that hits the network belongs behind #[ignore] or a feature so the default suite stays offline.
Code Examples
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 40), 42);
}
}Common Gotchas
Tests run in parallel
A test that writes `./tmp-config` without a unique name will flake. Use `tempfile`.
`#[test]` functions returning `Result` fail on `Err`
You can use `?`. Do not swallow the error with `let _ =`.