[−][src]Macro mockall::mock
Manually mock a structure.
Sometimes automock
can't be used. In those cases you can use
mock!
, which basically involves repeating the struct's or trait's
definitions.
The format is:
- Optional visibility specifier
- Real structure name and generics fields
- 0 or more methods of the structure, written without bodies, enclosed in a {} block
- 0 or more traits to implement for the structure, written like normal traits
Examples
Mock a trait. This is the simplest use case.
trait Foo { fn foo(&self, x: u32); } mock!{ pub MyStruct<T: Clone + 'static> { fn bar(&self) -> u8; } trait Foo { fn foo(&self, x: u32); } }
When mocking a generic struct's implementation of a generic trait,
use the same namespace for their generic parameters. For example,
if you wanted to mock Rc
, do
mock!{ pub Rc<T: 'static> {} trait AsRef<T> { fn as_ref(&self) -> &T; } }
not
ⓘThis example deliberately fails to compile
mock!{ pub Rc<Q: 'static> {} trait AsRef<T: 'static> { fn as_ref(&self) -> &T; } }
Associated types can easily be mocked by specifying a concrete type
in the mock!{}
invocation. But be careful not to reference the
associated type in the signatures of any of the trait's methods;
repeat the concrete type instead. For example, do:
mock!{ MyIter {} trait Iterator { type Item=u32; fn next(&mut self) -> Option<u32>; } }
not
ⓘThis example deliberately fails to compile
mock!{ MyIter {} trait Iterator { type Item=u32; fn next(&mut self) -> Option<<Self as Iterator>::Item>; } }