pub struct MockGuard<T: Mock> { /* private fields */ }
Expand description

Exclusive guard to set the mock state.

A guard can be used to check / adjust the mock state during the test. Dropping the guard also unsets the mock state, so that targeted functions are no longer mocked.

In case of shared mocks, guards also provided synchronization across concurrently executing tests: until a guard is dropped, other threads attempting to call Mock::set_as_mock() will block. Unfortunately, this is not always sufficient to have good results; see Shared docs for discussion.

Examples

#[mock(using = "ValueMock")]
fn answer() -> usize { 42 }

#[derive(Default, Mock)]
struct ValueMock(usize);

impl CheckRealCall for ValueMock {}

impl ValueMock {
    fn answer(&self) -> usize {
        self.0
    }
}

assert_eq!(answer(), 42);
let mut guard: MockGuard<_> = ValueMock::default().set_as_mock();
assert_eq!(answer(), 0);
guard.with(|mock| { mock.0 = 23; });
// ^ updates mock state without releasing the guard
assert_eq!(answer(), 23);

Implementations

Performs an action on the mock state without releasing the guard. This can be used to adjust the mock state, check or take some parts of it (such as collected args or responses).

Returns the enclosed mock state and releases the exclusive lock.

Trait Implementations

Formats the value using the given formatter. Read more

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

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.