skip to content

As the lead of a Rust service team, what rule would you set for test seams: generic parameters, trait objects, hand-written fakes or mockall?

level: principalimportance: should knowfreq 18%

answer

  1. seams at owned boundaries only
  2. generic by default, dyn by need
  3. fake for state, mock for interaction
  4. where the mock type is visible

basics

~20 s

Put traits only at boundaries tests must control: time, I/O, randomness. Default to a generic seam with a production default type and a shared fake, use mockall where the call itself is the behaviour, and decide which crates see the mocks.

solid answer

~40 s

My rule has four parts. Seams go only where tests need control the code cannot give them, such as the clock, the network, storage and randomness, never a trait per struct just to mock it. The seam is a generic parameter with a production default type, `TokenBucket<C: Clock = SystemClock>`, and becomes a `Box<dyn Clock + Send>` only when the implementation is picked at run time or the type parameter would spread through the app. A stateful collaborator gets one shared hand-written fake, which also suits proptest, and mockall is kept for tests where the interaction is the contract: exactly one `sleep_ms(70)`, no retry after an error. Finally, mock visibility: `#[cfg_attr(test, automock)]` hides `MockClock` from `tests/` and other crates, so anything shared goes in a test-support crate or behind a `mocks` feature.

code

toml · 14 lines
toml
[package]
name = "limiter"
version = "0.1.0"
edition = "2024"

[features]
mocks = ["dep:mockall"]

[dependencies]
mockall = { version = "0.13", optional = true }

[dev-dependencies]
proptest = "1"
mockall = "0.13"

go deeper

for a junior

Recall that Rust code becomes testable through a trait, and that a test can pass either a hand-written fake or a mockall-generated mock.

for a middle

Explain how a fake differs from a mock in Rust terms, and why a mock generated under cfg(test) is invisible to integration tests in tests/.

for a senior

Show the production costs of each seam, the visibility fix through a feature or a support crate, and how narrow expectations keep a suite stable through refactors.

for a principal

Own the rule: where seams may exist, the default seam shape, fake versus mock, and where test code lives, with the costs the team accepts written next to each choice.

## The decision has four parts A rule a team can enforce in review answers four questions, in this order: 1. **Where do seams exist?** Which collaborators get a trait at all. 2. **What shape is the seam?** A generic parameter or a trait object. 3. **What fills it in tests?** A hand-written fake, a mockall mock, or a real in-process implementation. 4. **Where does the test code live?** Which crates can see the fakes and mocks. The general argument about which collaborators deserve a stand-in belongs to testing theory. What follows is what each answer costs in Rust. ## Where seams exist In Rust, every seam is API. A trait adds a type parameter or a box to whatever holds it, and code that was a direct call becomes a trait method. A trait per struct, added only so that everything can be mocked, makes a codebase generic everywhere and gives its tests very little. Put seams where a test truly cannot get control otherwise: - **time**: a `Clock` with `now_ms()` and `sleep_ms()`, as in the token-bucket limiter; - **I/O**: network clients, storage, the filesystem; - **randomness and ids**: so a test can fix them; - **vendor clients**: behind a trait the team owns rather than the vendor's own types. ## What shape the seam takes Default to a **generic parameter with a production default**, `TokenBucket<C: Clock = SystemClock>`. It costs nothing at run time, keeps production signatures plain, accepts traits with generic methods, and lets a test lend `&MockClock` and inspect it afterwards. Allow a **`Box<dyn Clock + Send>` field** when the implementation is chosen at run time from configuration, or when a type parameter would have to thread through many layers of an application. The trade is a vtable call, a trait that must stay dyn compatible, and a mock the box owns until it drops. ## What fills the seam | | Hand-written fake | mockall mock | |---|---|---| | Models | behaviour: time that advances, a store that remembers | interactions: which calls, with what arguments, how often | | Suits proptest | yes, a fresh fake per case | awkward: a new set of expectations per case | | When the trait gains a method | the compiler makes you implement it | regenerated automatically | | Breaks on refactor | only when behaviour changes | when the call pattern changes, even if behaviour does not | | Failure message | your assertion | "No matching expectation found", count panics | The rule that falls out: **a fake for state, a mock for interaction**. Keep one `FakeClock`, a struct whose `sleep_ms` adds to a `Cell<u64>`, and reuse it everywhere. Reach for mockall when the call is the contract: the limiter sleeps once, for exactly the remaining 70 ms; the client never retries a 4xx. Even then, keep expectations narrow. Give incidental queries such as `now_ms()` a `return_const` with no `times`, and put counts only on the calls the test is about. ## Where the test code lives `#[cfg_attr(test, mockall::automock)]` with mockall in `[dev-dependencies]` is the README's pattern, and it has a boundary teams trip over. `cfg(test)` is set only for the crate being compiled as a test. An integration test in `tests/`, or another crate in the workspace, links the library built without it, so `use limiter::MockClock` fails with E0432. Three options: - **Keep mocks private.** Mocks used only by the crate's own unit tests stay behind `cfg(test)`. - **A `mocks` feature.** Make mockall an optional dependency enabled by a `mocks` feature and write `#[cfg_attr(any(test, feature = "mocks"), mockall::automock)]`. Consumers enable it from their `[dev-dependencies]`; Cargo's feature resolver (version 2, the 2021 default, and version 3 on 2024) keeps a feature turned on only by dev-dependencies out of normal builds. How features unify is Cargo's material. - **A test-support crate.** Shared fakes, and mocks if wanted, live in a separate workspace crate that every consumer takes as a dev-dependency, so production manifests never mention mockall. ## A rule worth writing down - Seams only at time, I/O, randomness and vendor boundaries; a new trait needs a test that could not be written without it. - Generic with a production default type; `dyn` when the implementation is chosen at run time or a parameter would spread. - A shared fake for every stateful seam; property tests use fakes. - mockall where the interaction is the assertion, with counts only on the calls under test. - Mocks behind `cfg(test)` unless another crate needs them; then a test-support crate, or a `mocks` feature. ## What the rule cannot settle Generic seams multiply monomorphised copies and compile time in large crates. A test-support crate is one more package to version. And no rule replaces judgment on a test whose expectations restate the implementation line by line. A reviewer should ask what behaviour it protects.

  • Three services in one workspace share the Clock trait. Would you expose the fakes and mocks through a mocks feature or a test-support crate?
    I would pick a test-support crate. Each service lists it under `[dev-dependencies]`, production manifests never mention mockall, and the shared `FakeClock` has one home. A `mocks` feature also works and keeps the code beside the trait, but every consumer must remember to enable it, and enabling it from a normal dependency by mistake would put mock code in a release build.
  • How do you stop a mockall-heavy suite from breaking on every refactor?
    Shrink the expectations to the contract. Incidental queries such as `now_ms()` get `return_const` with no `times`, and counts and argument matchers go only on the calls the test is about. Where a test's expectations mirror the implementation's call order, rewrite it against a fake and assert on outcomes; keep mocks for interactions that are the requirement.

  • Every struct should get a trait so anything can be mocked
  • mockall should replace hand-written fakes because mocks verify more
  • cfg_attr(test, automock) makes the mock usable from tests/ crates
  • A mocking crate can only fill a trait-object seam
  • The seam rule is test style and never changes production code