pub struct MockRef<T: Mock> { /* private fields */ }
Expand description
Reference to a mock state used when mocking async functions / methods.
A separate reference type is required because it would be unsound to spill a direct state reference
or a reference to Mut
across await
boundaries. (Internally, such a reference
is produced using interior mutability primitives like RefCell
.) Instead, MockRef
provides access to the state using with()
or with_mut()
methods that do not overly restrict the lifetime of the state reference.
Examples
Mock with immutable state
#[mock(using = "CountingMock")]
async fn answer() -> u32 { 42 }
#[derive(Default, Mock)]
struct CountingMock(AtomicU32);
impl CheckRealCall for CountingMock {}
impl CountingMock {
async fn answer(r: MockRef<Self>) -> u32 {
r.with(|this| this.0.fetch_add(1, Ordering::Relaxed))
}
}
Mock with mutable state
Also demonstrates spying logic.
#[mock(using = "CountingMock")]
async fn answer() -> u32 { 42 }
#[derive(Default, Mock)]
#[mock(mut)]
struct CountingMock {
captured_value: Option<u32>,
}
impl CountingMock {
#[async_recursion] // workaround for `async fn` recursion
async fn answer(r: MockRef<Self>) -> u32 {
let captured = r.with_mut(|this| this.captured_value);
if let Some(captured) = captured {
captured
} else {
let value = r.call_real().async_scope(answer()).await;
r.with_mut(|this| this.captured_value = Some(value));
value
}
}
}
let guard = CountingMock::default().set_as_mock();
assert_eq!(answer().await, 42);
let captured = guard.into_inner().captured_value;
assert_eq!(captured, Some(42));
Implementations
Trait Implementations
sourceimpl<T> CallReal for MockRef<T>where
T: Mock,
T::Base: CallReal,
impl<T> CallReal for MockRef<T>where
T: Mock,
T::Base: CallReal,
sourcefn call_real(&self) -> RealCallGuard<'_, Self>
fn call_real(&self) -> RealCallGuard<'_, Self>
Delegates all calls to the mocked functions / methods to the real implementation until
the returned
RealCallGuard
is dropped. Read moresourcefn call_real_once(&self) -> RealCallGuard<'_, Self>
fn call_real_once(&self) -> RealCallGuard<'_, Self>
Delegates the first call to the mocked functions / methods to the real implementation until
the returned
RealCallGuard
is dropped. Further calls will be directed to the mock. Read moreimpl<T: Mock> Copy for MockRef<T>
Auto Trait Implementations
impl<T> RefUnwindSafe for MockRef<T>where
<T as Mock>::Shared: UnwindSafe + RefUnwindSafe,
impl<T> Send for MockRef<T>
impl<T> Sync for MockRef<T>
impl<T> Unpin for MockRef<T>
impl<T> UnwindSafe for MockRef<T>where
<T as Mock>::Shared: UnwindSafe + RefUnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more