[][src]Macro double::mock_trait_no_default

macro_rules! mock_trait_no_default {
    ($mock_name:ident $(, $method:ident($($arg_type:ty),* ) -> $retval:ty )* ) => { ... };
    (pub $mock_name:ident $(, $method:ident($($arg_type:ty),* ) -> $retval:ty )* ) => { ... };
}

Macro that generates a struct implementation of a trait.

Use this instead of mock_trait! if one or more of the return types do not implement Default. If all return types implement Default, then it's more convenient to use mock_trait!, since you instantiate mock objects using default(),

This macro generates a struct that implements the traits Clone and and Debug. Create instances of the mock object by calling new(), passing in the return values for each mocked method using new().

The struct has a field for each method of the trait, which manages their respective method's behaviour and call expectations. For example, if one defines a mock like so:


// `Result` does not implement `Default`.
mock_trait_no_default!(
    MockTaskManager,
    max_threads(()) -> Result<u32, String>,
    set_max_threads(u32) -> ()
);

    // only here to make `cargo test` happy
}

Then the following code is generated:

#[derive(Debug, Clone)]
struct MockTaskManager {
    max_threads: double::Mock<(), Result<u32, String>>,
    set_max_threads: double::Mock<(u32), ()>,
}

impl MockTaskManager {
    pub fn new(max_threads: Result<u32, String>, set_max_threads: ()) -> Self {
        MockTaskManager {
            max_threads: double::Mock::new(max_threads),
            set_max_threads: double::Mock::new(set_max_threads),
        }
    }
}

Note that just defining this macro is not enough. This macro is used to generate the necessary boilerplate, but the generated struct does not implement the desired trait. To do that, use double's mock_method macro.

Examples


trait TaskManager {
   fn max_threads(&self) -> Result<u32, String>;
   fn set_max_threads(&mut self, max_threads: u32);
}

mock_trait_no_default!(
    MockTaskManager,
    max_threads(()) -> Result<u32, String>,
    set_max_threads(u32) -> ()
);

let mock = MockTaskManager::new(Ok(42), ());
assert_eq!(Ok(42), mock.max_threads.call(()));
mock.set_max_threads.call(9001u32);
assert!(mock.set_max_threads.called_with(9001u32));