Mock_derive 0.5 released. A Mocking library with basic generic support


mock_derive is a mocking library targeting nightly using procedural macros. Our github repo is over at The goal is that given a trait, mocking is as easy as adding #[mock]. We’ve just added (basic) support for generics, so we can mock a wider range of traits.

Our github has a host of examples, but I figured I would post a sample here to see what people think.

trait HelloWorld {
    fn return_int(&self) -> u32;
    fn int_option(&self) -> Option<u32>; 

fn it_works() {
    let foo = Foo::new();
    let mut mock = MockHelloWorld::new();
    mock.set_fallback(foo); // If a behavior isn't specified, we will fall back to this object's behavior.
    let method = mock.method_return_int()

    let result = mock.return_int();
    assert!(result == 3);
    let result2 = mock.return_int();
    assert!(result2 == 4);

    // This is a fallback case
    let result3 = mock.return_int();
    assert!(result3 == 1);

// You can also pass in a lambda to return a value. This can be used to return a value
// an infinite number of times
fn return_result_of() {
    let mut x = 15;
    let mut mock = MockHelloWorld::new();
    let method = mock.method_int_option()
        .return_result_of(move || {
            x += 1;

    assert!(mock.int_option() == Some(16));
    assert!(mock.int_option() == Some(17));
    assert!(mock.int_option() == Some(18));

// Generics work as well! 
trait GenericTrait<T, U>
      where T: Clone {
      fn merge(&self, t: T, u: U) -> U;

fn generic_test() {
    let mut mock = MockGenericTrait::<f32, i32>::new();
    let method = mock.method_merge()

    assert!(mock.merge(15.0, 15) == 30);