Mocking
A mock stands in for a dependency. In Rust you usually extract a trait, implement it for the real type and for a fake, and genericise (or Box<dyn>) the caller.
Detailed Explanation
Rust has no built-in mock framework and no runtime monkeypatching. You cannot replace File::open globally. You replace a trait. trait Clock { fn now(&self) -> u64; } with SystemClock in production and FixedClock { now: 1 } in tests. The function is fn expire<C: Clock>(c: &C, session: &Session). Tests pass FixedClock. That is the whole technique.
Crates such as mockall generate the fake from the trait and let you assert "save was called once with this id". They are useful when the protocol is rich. They are heavy when a ten-line struct would do. Prefer a handwritten fake for one or two methods. Reach for a crate when you are asserting call order on a busy trait.
#[cfg(test)] modules can supply fakes next to the code. Integration tests only see pub types, so the trait and a test-only constructor may need to be public, or the fake lives in the integration crate. Feature flags (test-utils) are another way to ship fakes without putting them in the default build.
Do not mock what you do not own if you can avoid it. Wrap the foreign type in your own trait at the boundary (a small facade) and fake that. Mocking a 40-method HTTP client trait you copied from a crate will break on every upgrade.
When you write a fake: time, I/O, payment providers. When you write a real integration: your database, if CI can run it. When you mock everything: the test documents the mocks, not the behaviour.
Code Examples
trait Clock {
fn now(&self) -> u64;
}
struct Fixed(u64);
impl Clock for Fixed {
fn now(&self) -> u64 {
self.0
}
}
fn is_expired<C: Clock>(clock: &C, expires_at: u64) -> bool {
clock.now() >= expires_at
}
fn main() {
println!("{}", is_expired(&Fixed(50), 40)); // prints: true
println!("{}", is_expired(&Fixed(10), 40)); // prints: false
}Common Gotchas
There is no monkeypatch
Extract a trait. If you cannot, the design is hard to test, not just the framework.
A generated mock can assert the wrong thing
"Called once" is not "the user is expired". Assert the outcome first, the calls second.
Do not make the production trait 30 methods wide for tests
Split traits (interface segregation). Fakes stay small.
`Box<dyn Clock>` is fine when generics leak too far
You pay a vtable and you keep the type out of every signature.