[][src]Crate faux

Faux

A library to create mocks out of structs.

faux provides macros to help you create mocks out of your structs without the need of generics/trait objects polluting your function signatures.

faux makes liberal use of unsafe rust features, and it is only recommended for use inside tests.

Usage:

// creates the mockable struct
#[cfg_attr(test, faux::create)]
pub struct Foo {
    a: u32,
}

// mocks the methods
#[cfg_attr(test, faux::methods)]
impl Foo {
    pub fn new(a: u32) -> Self {
        Foo { a }
    }

    pub fn add_stuff(&self, input: u32) -> u32 {
        self.a + input
    }

    pub fn add_ref(&self, input: &u32) -> u32 {
        self.a + *input
    }
}

#[cfg(test)]
#[test]
fn test() {
  // you can create the original object
  let real = Foo::new(3);
  assert_eq!(real.add_stuff(2), 5);

  // can create a mock using the auto-generated `faux` method
  let mut mock = Foo::faux();

  // if the inputs and output for a method are all static types
  // then it can be mocked safely
  faux::when!(mock.add_stuff).safe_then(|x| x);
  assert_eq!(mock.add_stuff(5), 5);

  // other methods can be mocked using unsafe
  unsafe { faux::when!(mock.add_ref).then(|&x| x + 1) }
  assert_eq!(mock.add_ref(&3), 4);
}

Features:

  • Mock async methods
  • Mock trait implementations
  • Mock generic structs
  • Mock methods with arbitrary self types (e.g., self: Rc<Self>). limited support
  • Mock methods from structs in a different module

Macros

when

Creates a When for a specific instance/method pair

Structs

When

Stores who and what to mock, how many times to mock it, and provides methods to mock the method both safely and unsafely.

WhenOnce

Similar to When but its methods will only make the mock active for a single call. This allows users to pass an FnOnce rather than an FnMut, thus allowing to move data into the closure through a move rather than only a borrow or mutable borrow.

Attribute Macros

create

Transforms the given struct into a mockable version of itself.

methods

Transforms the given methods into mockable versions of themselves and provides a new method to mock them.