Struct mimicry::Mut

source ·
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

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

Delegates all calls to the mocked functions / methods to the real implementation until the returned RealCallGuard is dropped. Read more
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 more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Converts to this type from the input type.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts to this type from the input type.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.