mercredi 14 novembre 2018

verify function called in rust

I have a function handle() that takes another function output() to perform output-related logic (.e.g. display to stdout):

fn handle(mut output: impl FnMut(String) -> ()) -> Result<(), String> {
    // do something that produces output string `message`
    Ok(output(message))
}

I'm trying to write an integration test for this function, where I define a stub output function, which saves the output string to local mutable variable:

#[test]
fn should_work() {
    let mut output_message = String::from("");
    let output = |message: String| {
        output_message = message;
    };

    let result = handle(output);

    assert!(result.is_ok());
    assert_eq!("blah", output_message);
}

However I have error: cannot borrow output_message as immutable because it is also borrowed as mutable

Is there any way I can test using this approach? I briefly searched for some mock crates but all of the crates don't seem to be updated very often and they are a bit overkill for my scenario anyway.

If not, any better alternative to test this function?

Aucun commentaire:

Enregistrer un commentaire