Struct mocktopus::mocking::MockContext
source · pub struct MockContext<'a> { /* private fields */ }
Expand description
MockContext
allows for safe capture of local variables.
It does this by forcing only mocking the actual function while in the body of run.
Examples
Simple function replacement:
use mocktopus::macros::mockable;
use mocktopus::mocking::{MockContext, MockResult};
#[mockable]
fn f() -> i32 {
0
}
MockContext::new()
.mock_safe(f, || MockResult::Return(1))
.run(|| {
assert_eq!(f(), 1);
});
Using local variables:
use mocktopus::macros::mockable;
use mocktopus::mocking::{MockContext, MockResult};
#[mockable]
fn as_str(s: &String) -> &str {
&s
}
let mut count = 0;
MockContext::new()
.mock_safe(as_str, |s| { count += 1; MockResult::Return(&s) })
.run(|| {
assert_eq!(as_str(&"abc".to_string()), "abc");
});
assert_eq!(count, 1);
Implementations§
source§impl<'a> MockContext<'a>
impl<'a> MockContext<'a>
sourcepub fn mock_safe<I: Tuple, O, F, M>(self, mockable: F, mock: M) -> Selfwhere
F: Mockable<I, O>,
M: FnMut<I, Output = MockResult<I, O>> + 'a,
pub fn mock_safe<I: Tuple, O, F, M>(self, mockable: F, mock: M) -> Selfwhere
F: Mockable<I, O>,
M: FnMut<I, Output = MockResult<I, O>> + 'a,
Set up a function to be mocked.
This function doesn’t actually mock the function. It registers it as a
function that will be mocked when run
is called.
sourcepub unsafe fn mock_raw<I: Tuple, O, F, M>(self, mockable: F, mock: M) -> Selfwhere
F: Mockable<I, O>,
M: FnMut<I, Output = MockResult<I, O>>,
pub unsafe fn mock_raw<I: Tuple, O, F, M>(self, mockable: F, mock: M) -> Selfwhere
F: Mockable<I, O>,
M: FnMut<I, Output = MockResult<I, O>>,
Set up a function to be mocked.
This is an unsafe version of mock_safe
,
without lifetime constraint on mock
sourcepub fn run<T, F: FnOnce() -> T>(self, f: F) -> T
pub fn run<T, F: FnOnce() -> T>(self, f: F) -> T
Run the function while mocking all the functions.
This function will mock all functions registered for mocking, run the function passed in, then deregister those functions. It does this in a panic-safe way. Note that functions are only mocked in the current thread and other threads may invoke the real implementations.
Register a function for mocking with mock_safe
.