Attribute Macro faux::create [−][src]
#[create]
Transforms a struct into a mockable version of itself.
An associated function called faux
is created for the tagged
struct, masking the original definition of the struct by changing
its name.
Use cargo-expand
to see the changes to your struct after macro
expansion.
Requirements
This macro deliberately fails to compile if any of the struct’s fields are not private. Otherwise, a user of the struct could try to access the field directly when it no longer exists in the transformed version.
Only methods within impl
blocks tagged by
#[methods]
may use the struct’s fields.
Examples
#[cfg_attr(test, faux::create)] pub struct MyStruct { a: i32, b: Vec<u32>, } #[cfg_attr(test, faux::methods)] impl MyStruct { /* methods go here */ } // creates a mock instance of MyStruct let my_mock = MyStruct::faux();
Attribute arguments
self_type
Customizes storage of real instances of the mockable struct.
If self_type
is set, it must be set to the same value in all
#[methods]
for this struct.
Explanation
By default, #[faux::create]
transform a struct from:
#[faux::create] struct MyStruct { /* fields */ }
into something like:
struct MyStruct(MaybeFaux); enum MaybeFaux { // when a mock is created we use this variant Mock(/* snip */), // when a real instance is created we use this variant // stores an owned instance of the struct // not a smart pointer to the struct Real(OriginalMyStruct), } // the definition of the original struct struct OriginalMyStruct { /* fields */ }
This works well when constructors of MyStruct
returns an owned
instance. There are some cases, however, where the constructor
returns a smart pointer (i.e., Rc<Self>
). To support such cases,
use this attribute argument to customize how faux
will wrap the
real instance of your struct.
Examples
use std::sync::Arc; #[faux::create(self_type = "Arc")] pub struct MyStruct { /* private fields */ } #[faux::methods(self_type = "Arc")] impl MyStruct { pub fn new() -> Arc<Self> { /* implementation */ } /* more methods */ }
Allowed values:
#[create(self_type = "Owned")]
(default)#[create(self_type = "Rc")]
#[create(self_type = "Arc")]
#[create(self_type = "Box")]