A new mocking library to mock functions without using trait

95 points Top_Square_5236 35 comments

Our team decided to open source this as we think it could benefit the whole rust community. Also we are seeking feedback from the community to make it better:
https://github.com/microsoft/injectorppforrust

In short, injectorpp allows you to mock functions without using trait.

For example, to write tests for below code:

fn try_repair() -> Result<(), String> {
    if let Err(e) = fs::create_dir_all("/tmp/target_files") {
        // Failure business logic here

        return Err(format!("Could not create directory: {}", e));
    }

    // Success business logic here

    Ok(())
}

You don't need trait. Below code just works

let mut injector = InjectorPP::new();
injector
    .when_called(injectorpp::func!(fs::create_dir_all::<&str>))
    .will_execute(injectorpp::fake!(
        func_type: fn(path: &str) -> std::io::Result<()>,
        when: path == "/tmp/target_files",
        returns: Ok(()),
        times: 1
    ));

assert!(try_repair().is_ok());

Share your thoughts. Happy to discuss