Struct Mock

Source
pub struct Mock<C, R>
where C: Clone, R: Clone,
{ /* private fields */ }
Expand description

Used for tracking function call arguments and specifying a predetermined return value or mock function.

See the crate documentation for more substantial examples, including some that demonstrate how to use Mock for methods that have multiple arguments as well as methods with argument or return types that do not implement Clone.

Implementations§

Source§

impl<C, R> Mock<C, R>
where C: Clone, R: Clone,

Source

pub fn new<T: Into<R>>(return_value: T) -> Self

Creates a new Mock that will return return_value.

Examples found in repository?
examples/uncloneable.rs (line 39)
37    fn default() -> Self {
38        MockFileSystem {
39            copy: Mock::new(Ok(())),
40        }
41    }
Source

pub fn call(&self, args: C) -> R

Use the Mock to return a value, keeping track of the arguments used.

Depending on what has most recently been called, this will return:

  • the return value specified at construction time
  • the return value specified via Mock::return_value or a derivative, such as Mock::return_some
  • the output of the function set via Mock::use_fn with the current arguments
  • the output of the closure set via Mock::use_closure with the current arguments
§Examples
use pseudo::Mock;

let mock = Mock::<&str, _>::new("return value");
assert_eq!(mock.call("something"), "return value");

mock.return_value("different value");
assert_eq!(mock.call("something"), "different value");

mock.use_fn(str::trim);
assert_eq!(mock.call("  test  "), "test");

mock.use_closure(Box::new(|x| x.trim_left()));
assert_eq!(mock.call("  test  "), "test  ");

mock.use_fn(str::trim);
assert_eq!(mock.call("  test  "), "test");
Examples found in repository?
examples/send.rs (line 16)
15    fn foo(&self) {
16        self.foo.call(())
17    }
More examples
Hide additional examples
examples/simple.rs (line 36)
35    fn greet<S: AsRef<str>>(&self, name: S) {
36        self.greet.call(name.as_ref().to_string())
37    }
examples/uncloneable.rs (line 29)
27    fn copy<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> io::Result<()> {
28        let args = (from.as_ref().to_path_buf(), to.as_ref().to_path_buf());
29        self.copy.call(args).map_err(|err| {
30            let (kind, description) = (err.kind, err.description);
31            io::Error::new(kind, description)
32        })
33    }
Source

pub fn return_value<T: Into<R>>(&self, return_value: T)

Override the initial return value.

§Examples
use pseudo::Mock;

let mock = Mock::<&str, &str>::new("original value");
mock.return_value("new value");

assert_eq!(mock.call("something"), "new value");
Source

pub fn use_fn(&self, mock_fn: fn(C) -> R)

Specify a function to determine the Mock’s return value based on the arguments provided to Mock::call.

Arguments of Mock::call are still tracked.

§Examples
use pseudo::Mock;

fn add_two(x: i64) -> i64 {
    x + 2
}

let mock = Mock::<i64, i64>::new(10);
mock.use_fn(add_two);

assert_eq!(mock.call(1), 3);
assert_eq!(mock.call(10), 12);

For functions with multiple arguments, use a tuple:

use pseudo::Mock;

fn add((x, y, z): (i64, i64, i64)) -> i64 {
    x + y + z
}

let mock = Mock::<(i64, i64, i64), i64>::default();
mock.use_fn(add);

assert_eq!(mock.call((1, 1, 1)), 3);
assert_eq!(mock.call((1, 2, 3,)), 6);
Source

pub fn use_closure(&self, mock_fn: Box<dyn Fn(C) -> R + Send + Sync>)

Specify a closure to determine the Mock’s return value based on the arguments provided to Mock::call.

Arguments of Mock::call are still tracked.

§Examples
use pseudo::Mock;

let mock = Mock::<i64, i64>::new(10);
let add_two = |x| x + 2;
mock.use_closure(Box::new(add_two));

assert_eq!(mock.call(1), 3);
assert_eq!(mock.call(10), 12);

For functions with multiple arguments, use a tuple:

use pseudo::Mock;

let mock = Mock::<(i64, i64, i64), i64>::default();
let add = |(x, y, z)| x + y + z;
mock.use_closure(Box::new(add));

assert_eq!(mock.call((1, 1, 1)), 3);
assert_eq!(mock.call((1, 2, 3,)), 6);
Source

pub fn called(&self) -> bool

Returns true if Mock::call has been called.

§Examples
use pseudo::Mock;

let mock = Mock::<i64, ()>::default();

assert!(!mock.called());

// mock.call(10);

// assert!(mock.called());
Source

pub fn num_calls(&self) -> usize

Returns the number of times Mock::call has been called.

§Examples
use pseudo::Mock;

let mock = Mock::<i64, i64>::new(0);

assert_eq!(mock.num_calls(), 0);
mock.call(5);
assert_eq!(mock.num_calls(), 1);
mock.call(10);
assert_eq!(mock.num_calls(), 2);
Examples found in repository?
examples/simple.rs (line 54)
48fn main() {
49    let mock = MockDependency::default();
50    let consumer = Consumer::new(&mock);
51
52    consumer.greet_everyone(vec!["Fido", "Spot", "Princess"]);
53
54    assert_eq!(mock.greet.num_calls(), 3);
55
56    assert!(mock.greet.called_with("Fido"));
57    assert!(mock.greet.called_with("Spot"));
58    assert!(mock.greet.called_with("Princess"));
59}
More examples
Hide additional examples
examples/uncloneable.rs (line 70)
62fn main() {
63    // Initially, the `copy` mock returns `Ok()`
64    let mock = MockFileSystem::default();
65
66    let result = copy_to_all(&mock, "from", &["to"]);
67
68    assert!(result.iter().all(|res| res.is_ok()));
69
70    assert_eq!(mock.copy.num_calls(), 1);
71    let expected_args = (
72        Path::new("from").to_path_buf(),
73        Path::new("to").to_path_buf(),
74    );
75    assert!(mock.copy.called_with(expected_args));
76
77    let err = CloneableError {
78        kind: ErrorKind::NotFound,
79        description: "test",
80    };
81    mock.copy.return_err(err);
82
83    let result = copy_to_all(&mock, "from", &["to"]);
84
85    assert!(result.iter().all(|res| res.is_err()));
86}
Source

pub fn calls(&self) -> Vec<C>

Returns the arguments to Mock::call in order from first to last.

§Examples
use pseudo::Mock;

let mock = Mock::<&str, &str>::new("");

mock.call("first");
mock.call("second");
mock.call("third");

assert_eq!(mock.calls().as_slice(), ["first", "second", "third"]);
Source

pub fn reset_calls(&self)

Reset the call history for the Mock.

§Examples
use pseudo::Mock;

let mock = Mock::<&str, &str>::default();

mock.call("first");
mock.call("second");

assert!(mock.called());
assert_eq!(mock.num_calls(), 2);
assert!(mock.called_with("first"));
assert!(mock.called_with("second"));

mock.reset_calls();

assert!(!mock.called());
assert_eq!(mock.num_calls(), 0);
assert!(!mock.called_with("first"));
assert!(!mock.called_with("second"));
Source§

impl<C, R> Mock<C, R>
where C: Clone + PartialEq, R: Clone,

Source

pub fn called_with<T: Into<C>>(&self, args: T) -> bool

Returns true if the specified argument has been used for Mock::call.

§Examples
use pseudo::Mock;

let mock = Mock::<&str, ()>::new(());
mock.call("foo");
mock.call("bar");

assert!(mock.called_with("foo"));
assert!(mock.called_with("bar"));
assert!(!mock.called_with("baz"));
Examples found in repository?
examples/simple.rs (line 56)
48fn main() {
49    let mock = MockDependency::default();
50    let consumer = Consumer::new(&mock);
51
52    consumer.greet_everyone(vec!["Fido", "Spot", "Princess"]);
53
54    assert_eq!(mock.greet.num_calls(), 3);
55
56    assert!(mock.greet.called_with("Fido"));
57    assert!(mock.greet.called_with("Spot"));
58    assert!(mock.greet.called_with("Princess"));
59}
More examples
Hide additional examples
examples/uncloneable.rs (line 75)
62fn main() {
63    // Initially, the `copy` mock returns `Ok()`
64    let mock = MockFileSystem::default();
65
66    let result = copy_to_all(&mock, "from", &["to"]);
67
68    assert!(result.iter().all(|res| res.is_ok()));
69
70    assert_eq!(mock.copy.num_calls(), 1);
71    let expected_args = (
72        Path::new("from").to_path_buf(),
73        Path::new("to").to_path_buf(),
74    );
75    assert!(mock.copy.called_with(expected_args));
76
77    let err = CloneableError {
78        kind: ErrorKind::NotFound,
79        description: "test",
80    };
81    mock.copy.return_err(err);
82
83    let result = copy_to_all(&mock, "from", &["to"]);
84
85    assert!(result.iter().all(|res| res.is_err()));
86}
Source§

impl<C, S> Mock<C, Option<S>>
where C: Clone, S: Clone,

Source

pub fn return_some<T: Into<S>>(&self, return_value: T)

Return Some(return_value) from Mock::call.

§Examples
use pseudo::Mock;

let mock = Mock::<(), Option<i64>>::new(None);
mock.return_some(10);

assert_eq!(mock.call(()), Some(10));
Source

pub fn return_none(&self)

Return None from Mock::call.

§Examples
use pseudo::Mock;

let mock = Mock::<(), Option<i64>>::new(Some(42));
mock.return_none();

assert_eq!(mock.call(()), None);
Source§

impl<C, O, E> Mock<C, Result<O, E>>
where C: Clone, O: Clone, E: Clone,

Source

pub fn return_ok<T: Into<O>>(&self, return_value: T)

Return Ok(return_value) from Mock::call.

§Examples
use pseudo::Mock;

let mock = Mock::<(), Result<&str, &str>>::new(Err("oh no"));
mock.return_ok("success");

assert_eq!(mock.call(()), Ok("success"));
Source

pub fn return_err<T: Into<E>>(&self, return_value: T)

Return Err(return_value) from Mock::call.

§Examples
use pseudo::Mock;

let mock = Mock::<(), Result<&str, &str>>::new(Ok("success"));
mock.return_err("oh no");

assert_eq!(mock.call(()), Err("oh no"));
Examples found in repository?
examples/uncloneable.rs (line 81)
62fn main() {
63    // Initially, the `copy` mock returns `Ok()`
64    let mock = MockFileSystem::default();
65
66    let result = copy_to_all(&mock, "from", &["to"]);
67
68    assert!(result.iter().all(|res| res.is_ok()));
69
70    assert_eq!(mock.copy.num_calls(), 1);
71    let expected_args = (
72        Path::new("from").to_path_buf(),
73        Path::new("to").to_path_buf(),
74    );
75    assert!(mock.copy.called_with(expected_args));
76
77    let err = CloneableError {
78        kind: ErrorKind::NotFound,
79        description: "test",
80    };
81    mock.copy.return_err(err);
82
83    let result = copy_to_all(&mock, "from", &["to"]);
84
85    assert!(result.iter().all(|res| res.is_err()));
86}

Trait Implementations§

Source§

impl<C, R> Clone for Mock<C, R>
where C: Clone + Clone, R: Clone + Clone,

Source§

fn clone(&self) -> Mock<C, R>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<C, R> Debug for Mock<C, R>
where C: Clone + Debug, R: Clone + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C, R> Default for Mock<C, R>
where C: Clone, R: Clone + Default,

Source§

fn default() -> Self

Use R::default() as the initial return value.

§Examples
use pseudo::Mock;

let mock = Mock::<i64, i64>::default();
assert_eq!(mock.call(10), 0);

let mock = Mock::<(), String>::default();
assert_eq!(&mock.call(()), "");

let mock = Mock::<(i64, &str), Option<bool>>::default();
assert_eq!(mock.call((10, "test")), None);

Auto Trait Implementations§

§

impl<C, R> Freeze for Mock<C, R>

§

impl<C, R> RefUnwindSafe for Mock<C, R>

§

impl<C, R> Send for Mock<C, R>
where R: Send + Sync, C: Send + Sync,

§

impl<C, R> Sync for Mock<C, R>
where R: Send + Sync, C: Send + Sync,

§

impl<C, R> Unpin for Mock<C, R>

§

impl<C, R> UnwindSafe for Mock<C, R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.