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 real_switch(&self) -> &RealCallSwitch
fn real_switch(&self) -> &RealCallSwitch
Returns a reference to the call switch.
sourcefn call_real<R>(&self, action: impl FnOnce() -> R) -> R
fn call_real<R>(&self, action: impl FnOnce() -> R) -> R
Runs the provided closure with all calls to the mocked function / method being directed to “real” implementation. Read more
sourcefn call_real_once<R>(&self, action: impl FnOnce() -> R) -> R
fn call_real_once<R>(&self, action: impl FnOnce() -> R) -> R
Runs the provided closure with the first call to the mocked function / method being directed to “real” implementation. Further calls will be directed to the mock. Read more
Auto 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 T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
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