Macro double::mock_trait
[−]
[src]
macro_rules! mock_trait { ($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_no_default!
if all mocked method return
types implement Default
. If one or more of the return types do not
implement Default
, then mock_trait_no_default!
must be used to generate
the mock.
This macro generates a struct
that implements the traits Clone
, Debug
and Default
. Create instances of the mock object by calling the
struct
's default()
method, or specify custom default 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:
mock_trait!( MockTaskManager, max_threads(()) -> u32, 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<(), u32>, set_max_threads: double::Mock<(u32), ()>, } impl Default for MockTaskManager { fn default() -> Self { MockTaskManager { max_threads: double::Mock::default(), set_max_threads: double::Mock::default(), } } }
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) -> u32; fn set_max_threads(&mut self, max_threads: u32); } mock_trait!( MockTaskManager, max_threads(()) -> u32, set_max_threads(u32) -> () ); let mock = MockTaskManager::default(); mock.max_threads.return_value(42u32); assert_eq!(42, mock.max_threads.call(())); mock.set_max_threads.call(9001u32); assert!(mock.set_max_threads.called_with(9001u32));