Attribute Macro automock
#[automock]
Expand description
Automatically generate mock types for structs and traits.
This is by far the easiest way to use Mockall. It works on almost all
traits, and almost all structs that have a single impl
block. In either
case, it will generate a mock struct whose name is the name of the mocked
struct/trait prepended with “Mock”. For each method of the original, the
mock struct will have a method named expect_whatever
that allows you to
set expectations. There will also be one checkpoint
method that calls
checkpoint
for every single mocked method.
§Examples
The simplest use case is mocking a no-frills trait
#[automock]
pub trait Foo {
fn foo(&self, key: i16);
}
let mock = MockFoo::new();
Mocking a structure:
struct Foo {}
#[automock]
impl Foo {
fn foo(&self) -> u32 {
// ...
}
}
You can also mock a trait impl on a struct:
pub trait Foo {
fn foo(&self, key: i16);
}
struct Bar{}
#[automock]
impl Foo for Bar {
fn foo(&self, key: i16){
// ...
}
}
let mock = MockBar::new();
Mocking a trait with associated types requires adding a metaitem to the attribute:
#[automock(type Item=u32;)]
trait Foo {
type Item;
fn foo(&self) -> Self::Item;
}
Finally, #[automock]
can also mock foreign functions. This requires
another metaitem to specify the mock module name.
#[automock(mod mock_ffi;)]
extern "C" {
pub fn foo() -> u32;
}
§Limitations
#[automock]
can’t handle everything. There are some cases where
you will need to use mock
instead:
- Mocking a struct that has multiple
impl
blocks, including structs that implement traits. - Mocking a struct or trait defined in another crate.
- Mocking a trait with trait bounds.
- If the autogenerated “MockFoo” name isn’t acceptable, and you want to choose your own name for the mock structure.