Testing
`#[test]`, the assert macros, `#[should_panic]`, integration and doc tests, and how Rust code is mocked.
7 questions
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It compiles and panics
Open full question →Common mistakes
- ✗Expecting
done, as if a failed assertion were a warning or skipped outside tests:assert_eq!always runs and panics when the two sides differ. - ✗Expecting a build error because
assert_eq!lives only in#[test]functions: it is a normal macro and works inmaintoo.
Follow-up questions
- →What two value lines does the panic message show, and which side is
left? - →Inside a
#[test]function, what wouldcargo testreport for this assertion?
JuniorTheoryCommonWhere do unit, integration and doc tests live in Rust, and what can each see?
Where do unit, integration and doc tests live in Rust, and what can each see?
Unit tests live in a #[cfg(test)] module beside the code and may call private items. Integration tests are files in tests/, each its own crate that sees only the public API. Doc tests are code blocks in /// comments that cargo test runs.
Common mistakes
- ✗Calling a private function from a file in
tests/: it is a separate crate, so the call fails with E0603 (function is private) - ✗Treating
///examples as plain text:cargo testcompiles and runs each code block, so a stale example fails the build - ✗Expecting an integration test to reach a binary crate's
main.rsfunctions: only a library crate exposes items totests/
Follow-up questions
- →How do you share a helper between several files in
tests/without it running as a test? - →Which kind of test would you write first for a new public function, and why?
JuniorTheoryCommonHow do you write a unit test in Rust, and what does cargo test run?
How do you write a unit test in Rust, and what does cargo test run?
A test is a #[test] function in a #[cfg(test)] mod tests; it fails if it panics, which assert!, assert_eq! and assert_ne! do when a check fails. cargo test runs all tests in parallel; cargo test add keeps names containing add.
Common mistakes
- ✗Expecting a failed
assert_eq!to only log the mismatch: it panics, and the panic is what marks the test as failed - ✗Assuming tests run one after another in a fixed order, then sharing a file or a global between them: they run in parallel threads
- ✗Reading
cargo test addas an exact name: it is a substring filter and also runsadds_wrongortests::add_two
Follow-up questions
- →Why does a helper used only by tests trigger a
dead_codewarning without#[cfg(test)]? - →How do you run the tests on one thread and see the
println!output of passing tests?
MiddleTheoryCommonWhat do #[should_panic], #[ignore] and a Result return change in a test?
What do #[should_panic], #[ignore] and a Result return change in a test?
#[should_panic(expected = "msg")] passes only on a panic whose message contains msg. #[ignore] skips a test unless you run cargo test -- --ignored. A test returning Result<(), E> fails on Err, so it can use ?, but not #[should_panic].
Common mistakes
- ✗Writing a bare
#[should_panic]: any panic passes it, including one from the wrong line, so a broken test stays green;expectedpins the message - ✗Expecting
expectedto match the whole message: it is a substring check, and a mismatch reportspanic did not contain expected string - ✗Adding
#[should_panic]to a test that returnsResult: rustc refuses withfunctions using #[should_panic] must return ()
Follow-up questions
- →How do you run the ignored tests together with the rest in one
cargo testcall? - →How would you check that a
Result-returning function fails, without#[should_panic]?
MiddleTheoryOccasionalBeyond #[test], what do property tests, fuzzing, the undefined-behaviour checker Miri and benchmarks catch?
Beyond #[test], what do property tests, fuzzing, the undefined-behaviour checker Miri and benchmarks catch?
proptest checks an invariant on many generated inputs and shrinks a failure to a minimal case; cargo fuzz mutates inputs, led by coverage, to find panics and crashes; Miri flags undefined behaviour in unsafe code; criterion catches slowdowns.
Common mistakes
- ✗Treating Miri as a static proof: it only checks the paths the tests actually execute, so untested
unsafecode can still hide undefined behaviour - ✗Writing property tests that restate the implementation instead of an independent invariant such as a round trip or a sort order
- ✗Timing code with
Instant::now()in a debug build instead of a statistical benchmark on an optimised build
Follow-up questions
- →What does shrinking in the property-testing crate
proptestdo when it finds a failing input? - →Why do the fuzzing tool
cargo fuzzand the interpreter Miri need a nightly toolchain?
MiddleDesignOccasionalA CheckoutService charges cards through a payment provider's HTTP API. You must unit-test its logic: a successful charge, a declined card, a timeout that is retried exactly once, and a refund that is never sent twice. Constraints: CI has no network access, the tests must be fast and deterministic, and the production path should not pay for dynamic dispatch unless you can justify it. Explain how you make the HTTP client replaceable, what the test double looks like (a hand-written fake or a mock library), whether you inject it as a generic parameter or as dyn Trait, and what you still test against the real API.
A CheckoutService charges cards through a payment provider's HTTP API. You must unit-test its logic: a successful charge, a declined card, a timeout that is retried exactly once, and a refund that is never sent twice. Constraints: CI has no network access, the tests must be fast and deterministic, and the production path should not pay for dynamic dispatch unless you can justify it. Explain how you make the HTTP client replaceable, what the test double looks like (a hand-written fake or a mock library), whether you inject it as a generic parameter or as dyn Trait, and what you still test against the real API.
Put the client behind a PaymentClient trait and make the service generic over it, with dyn only for a client picked at run time. Tests inject a fake with scripted replies that records calls, or a mockall mock; ignored tests hit the sandbox.
Common mistakes
- ✗Branching on
#[cfg(test)]inside the real client: the tests then exercise a code path production never runs - ✗Assuming a mock needs
dyn Trait: a fake or amockallmock fills a generic parameter just as well, with static dispatch - ✗Trusting the fake alone: it encodes your reading of the provider's API, so a few real sandbox calls must still check the contract
Follow-up questions
- →How would the fake check that a refund is never sent twice when a retry happens?
- →When would the mocking crate
mockallbeat a hand-written fake, and when the other way round?
SeniorTheoryOccasionalHow does the concurrency checker loom find interleaving bugs, and where does it fall short?
How does the concurrency checker loom find interleaving bugs, and where does it fall short?
Under #[cfg(loom)] code uses loom's Arc, Mutex, atomics, threads, and loom::model reruns the test over each distinct interleaving and atomic value. It fits only tiny tests, as states explode, and it does not model every weak-memory effect.
Common mistakes
- ✗Running a loom test over code that still imports
std::syncdirectly: loom only controls its own types, so those accesses are never permuted - ✗Writing a loom model with many threads and long loops: the number of executions explodes, so keep two or three threads and a few operations
- ✗Treating a green loom run as proof: a preemption bound or an unmodelled weak-memory effect can leave real executions unexplored
Follow-up questions
- →How do you switch a crate between std and loom types with a
cfgflag? - →What does the
LOOM_MAX_PREEMPTIONSenvironment variable trade away?