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 https://github.com/DavidDeSimone/mockitol. 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.

#[mock]
trait HelloWorld {
    fn return_int(&self) -> u32;
    fn int_option(&self) -> Option<u32>; 
}

#[test]
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()
        .second_call()
        .set_result(4)
        .first_call()
        .set_result(3);

    mock.set_return_int(method);
    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
#[test]
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;
            Some(x)
    });

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

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

#[test]
fn generic_test() {
    let mut mock = MockGenericTrait::<f32, i32>::new();
    let method = mock.method_merge()
        .called_once()
        .set_result(30);

    mock.set_merge(method);
    assert!(mock.merge(15.0, 15) == 30);
}
1 Like