pub struct Mut<T> { /* private fields */ }
Expand description
A lightweight wrapper around the state (essentially, a RefCell
) allowing to easily
mutate it in mock code.
Besides access to the state, Mut
implements CallReal
, thus allowing
partial mocks / spies.
Examples
#[mock(using = "CounterMock")]
fn answer() -> usize { 42 }
#[derive(Default, Mock)]
#[mock(mut)] // indicates to use `Mut`
struct CounterMock(usize);
impl CounterMock {
fn answer(this: &Mut<Self>) -> usize {
// Note a custom "receiver" instead of `&self`
this.borrow().0 += 1;
this.borrow().0
}
}
let guard = CounterMock::default().set_as_mock();
assert_eq!(answer(), 1);
assert_eq!(answer(), 2);
assert_eq!(answer(), 3);
assert_eq!(guard.into_inner().0, 3);
Implementations
sourceimpl<T> Mut<T>
impl<T> Mut<T>
sourcepub fn borrow(&self) -> impl DerefMut<Target = T> + '_
pub fn borrow(&self) -> impl DerefMut<Target = T> + '_
Returns an exclusive reference to the underlying mock.
Beware that while the reference is alive, further calls to functions in the same mock
(including indirect ones, e.g., performed from the tested program code)
will not be able to retrieve the state via this method; this will result
in a panic. To deal with this, you can create short lived state refs a la
this.borrow().do_something()
, or enclose the reference into an additional scope.
Panics
Panics if a reference to the same mock state is alive, as described above.
Trait Implementations
sourceimpl<T> CallReal for Mut<T>
impl<T> CallReal for Mut<T>
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 moreAuto Trait Implementations
impl<T> !RefUnwindSafe for Mut<T>
impl<T> Send for Mut<T>where
T: Send,
impl<T> !Sync for Mut<T>
impl<T> Unpin for Mut<T>where
T: Unpin,
impl<T> UnwindSafe for Mut<T>where
T: UnwindSafe,
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