ownership

Rust Recording calls in a mock

A test double can record calls through an interface that accepts a shared receiver. Keep this mutation local to the mock and inspect it after the call. A real implementation may need different synchronization or error-handling choices. Expected output (not executed): recorded Why: The mock observes calls without changing the trait receiver. Common mistake: Holding an inspection guard while calling a method that records another message.

Formal Syntax & Structure

rust syntaxrust
fn send(&self, message: &str)

Working Example

Example Snippetrust
use std::cell::RefCell;trait Sender { fn send(&self, message: &str); }struct Recorder { sent: RefCell<Vec<String>> }impl Sender for Recorder {    fn send(&self, message: &str) { self.sent.borrow_mut().push(message.to_owned()); }}fn main() {    let mock = Recorder { sent: RefCell::new(Vec::new()) };    mock.send("ready");    assert_eq!(mock.sent.borrow().as_slice(), &[String::from("ready")]);    println!("recorded");}
Rust Reference