pub struct Spy<T: Clone> { /* private fields */ }Expand description
Call recorder that carries a wrapped value alongside it.
§This does not intercept anything
Spy is a manual recorder, not a proxy. Wrapping a value does not make
its methods observable: Spy::inner hands back the value untouched, and
calls made through that reference go straight to it. Recording happens only
where you call Spy::record yourself:
#[derive(Clone)]
struct Repo;
impl Repo {
fn find(&self, id: u32) -> String { format!("user-{id}") }
}
let spy = Spy::new(Repo);
// The call is recorded because the test records it, not because `Spy` saw it.
spy.record("find");
let user = spy.inner().find(7);
assert_eq!(user, "user-7");
assert_eq!(spy.call_count(), 1);
assert!(spy.was_called("find"));For automatic interception, implement the trait under test on a hand-written
fake that records in each method - Spy is then useful as that fake’s
storage.
Cloning a Spy shares the recording buffer, so a clone handed to production
code records into the same log the test asserts on.
Implementations§
Source§impl<T: Clone> Spy<T>
impl<T: Clone> Spy<T>
Sourcepub fn record(&self, method: &str)
pub fn record(&self, method: &str)
Record a method call.
Call this yourself at each site you want observed; Spy cannot see
calls made through Spy::inner.
Sourcepub fn call_count(&self) -> usize
pub fn call_count(&self) -> usize
Get the number of recorded calls
Sourcepub fn was_called(&self, method: &str) -> bool
pub fn was_called(&self, method: &str) -> bool
Check if a method was recorded as called