In Rust, what does mockall's `#[automock]` on a `Clock` trait generate, and what do `expect_now_ms()`, `times`, `returning` and `with` configure?
answer
- Mock plus the trait name
- one expect_ method per trait method
- every expectation needs a return value
- extra calls now, missing calls at drop
basics
~10 s#[automock] generates MockClock, a struct implementing Clock. expect_now_ms() adds an expectation; returning or return_const sets its result, with or withf matches arguments, and times sets a count checked at each call and at drop.
solid answer
~40 s`#[automock]` on `trait Clock` generates `MockClock` with `new()` and `Default`, an `impl Clock for MockClock`, and one `expect_<method>()` per trait method. Each call to `expect_now_ms()` pushes an expectation you configure in a chain: `returning(closure)` or `return_const(value)` for the result, which every expectation needs unless the crate's nightly feature is on; `with(eq(70))` or `withf(|ms| *ms == 70)` to match arguments; and `times(1)`, a range, `once()` or `never()` for the call count, which is otherwise unlimited. A call no expectation matches panics with "No matching expectation found". Exceeding a count panics at the call; falling short panics when the mock is dropped, typically when the bucket that owns it goes out of scope. Written as `#[cfg_attr(test, mockall::automock)]` with mockall in `[dev-dependencies]`, the mock exists only in test builds.
code
rust · 5 lines#[cfg_attr(test, mockall::automock)]
pub trait Clock {
fn now_ms(&self) -> u64;
fn sleep_ms(&self, ms: u64);
}go deeper
Recall that #[automock] on a trait generates a MockTraitName struct, and that you set results with expect_method().returning(..) or return_const(..).
Explain matching order, the default unlimited count, times and with, and why a too-few count is reported only when the mock drops.
Diagnose mock failures from their messages, keep expectations to the contract under test, and handle Send bounds, checkpoints and the panics that hide later ones.
Judge where interaction checks earn their brittleness in a suite and where a fake or a real in-process implementation gives sturdier evidence.
## What `#[automock]` generates **mockall** is a crate whose attribute macro writes a mock type at compile time. Put `#[automock]` on a trait and it generates a struct named after the trait with `Mock` prepended, here `MockClock`, plus: - `MockClock::new()` and a `Default` impl; - an `impl Clock for MockClock`, so the mock goes anywhere a `Clock` is accepted; - one `expect_<method>()` per trait method, here `expect_now_ms()` and `expect_sleep_ms()`, each returning an `Expectation` to configure; - `checkpoint()`, which verifies every expectation immediately and then clears them. The README's usage pattern is `#[cfg_attr(test, automock)]`, spelled `mockall::automock` here, with mockall under `[dev-dependencies]`, so production builds never compile the mock or link the crate. How `cfg_attr` works is covered with conditional compilation; what matters here is that the mock exists only while the crate builds its own unit tests. ## Building an expectation Each `expect_now_ms()` call adds one expectation, configured by chaining methods on it: | Method | Sets | Bound on what you pass | |---|---|---| | `returning(closure)` | the result, computed from the arguments taken by value | `FnMut + Send + 'static` | | `return_const(value)` | a fixed result, cloned on each call | `Clone + Send + 'static` | | `return_once(closure)` | a result for exactly one call, for values that are not `Clone` | `FnOnce + Send + 'static` | | `with(eq(70))` | argument matchers built from `mockall::predicate` | one predicate per argument | | `withf(closure)` | a matcher taking the arguments by reference | `Fn(&u64) -> bool + Send + 'static` | | `times(n)`, `times(2..=3)`, `once()`, `never()` | the call count | a number or any integer range | Mock objects are always `Send`, which is why the closures must be `Send`. A `returning` closure that captures an `Rc<Cell<u64>>` fails with E0277, "`Rc<Cell<u64>>` cannot be sent between threads safely"; the `_st` variants such as `returning_st` accept non-`Send` values and panic if they are touched from another thread. ## How calls are matched When the code under test calls `now_ms()`, the mock walks that method's expectations in the order they were added and uses the **first one whose matchers accept the arguments**. An expectation that has reached its maximum count is skipped while another one exists. So three expectations, `times(1).return_const(0)`, `times(1).return_const(30)` and an unbounded `return_const(100)`, answer 0, then 30, then 100 forever. A common layout lists specific expectations first and a catch-all last. Without `times`, an expectation accepts **any number of calls, including zero**, so an unused catch-all never fails a test. ## When a mock panics All five failure modes below were produced with the `MockClock` in this answer: 1. **No expectation matches.** A call with no expectation at all, or with arguments no matcher accepts, panics at the call: `MockClock::sleep_ms(69): No matching expectation found`. 2. **No return value.** Without the crate's nightly feature, calling an expectation that has no `returning` or `return_const` panics with `Returning default values requires the "nightly" feature`. The compiler warns first: the result of `expect_now_ms()` is marked must-use with the note `Must set return value when not using the "nightly" feature`. 3. **Too many calls.** The call that exceeds the count panics on the spot. 4. **Too few calls.** This can only be judged when no more calls can come, so the expectation checks its count in its `Drop` impl: when the mock drops, typically with the struct that owns it, the test panics with "called 0 time(s) which is fewer than expected 1". 5. **`never()` violated.** The first call panics with "should not have been called". The `Drop` check is skipped if the thread is already panicking. A test that fails an assertion therefore reports only that assertion, and when several counts fall short, only the first expectation to drop is reported. ## Reading the example test The test checks the waiting path of `acquire()` on a bucket with capacity 1 and a 100 ms refill: 1. `TokenBucket::new` reads the clock once: 0. 2. The first `acquire()` reads 0 and takes the only token. 3. The second `acquire()` reads 30, finds the bucket empty and calls `sleep_ms(70)`, the time left until the next refill. `with(eq(70))` pins the argument and `times(1)` the count. 4. The loop reads 100, one token is refilled, and `acquire()` returns. 5. At the closing brace the bucket drops, the mock drops with it, and both counts are verified. The test asserts no return values of its own. The interaction is the behaviour: exactly one sleep, of exactly the remaining gap. That is the job a mock does better than a fake clock, which would accept any sleep.
- Why does a missing sleep_ms call fail the test at the closing brace rather than at a call?A count that is too low can only be judged once no more calls can arrive. mockall checks it in the expectation's `Drop`, which runs when the mock drops, usually with the bucket that owns it. Call `checkpoint()` to verify earlier, which needs mutable access to the mock. If the thread is already panicking, the check is skipped so the first failure stays readable.
- A returning closure captures an Rc<Cell<u64>> to share the time with the test. Why does it not compile, and what are the options?`returning` requires `FnMut + Send + 'static`, because mock objects are always `Send`, and `Rc` is not `Send`, so rustc reports E0277. Use `returning_st`, which accepts non-`Send` closures and panics on cross-thread use, or share an `Arc<AtomicU64>` instead. For time that the test drives, a hand-written fake clock is often simpler than either.
- How do you make now_ms return 0, then 30, then 100 on successive calls?Either one `returning` closure that pulls from an iterator moved into it, or several expectations with `times(1)` added in order plus a final unbounded one. mockall uses the first matching expectation and skips one whose exact count is used up, so the three answer in sequence. The closure keeps the readings in one place.
- mockall mocks methods by intercepting calls on the real struct at run time
- An expectation without times(..) must be called exactly once
- A missing call fails at the line where it should have happened
- Expectations with no return value return Default on stable Rust
- returning closures may capture Rc because mocks stay on one thread