mockall

Macro mock

mock!() { /* proc-macro */ }
Expand description

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 impl blocks implementing traits on the structure, also without bodies.

§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;
    }
    impl Foo for MyStruct {
        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> {}
    impl<T: 'static> AsRef<T> for Rc<T> {
        fn as_ref(&self) -> &T;
    }
}

not

mock!{
    pub Rc<Q: 'static> {}
    impl<T: 'static> AsRef<T> for Rc<T> {
        fn as_ref(&self) -> &T;
    }
}

Associated types can easily be mocked by specifying a concrete type in the mock!{} invocation.

mock!{
    MyIter {}
    impl Iterator for MyIter {
        type Item=u32;

        fn next(&mut self) -> Option<<Self as Iterator>::Item>;
    }
}