I have a function that takes a closure 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`
let message = "example".to_string();
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:
error[E0502]: cannot borrow `output_message` as immutable because it is also borrowed as mutable
--> src/lib.rs:18:24
|
11 | let output = |message: String| {
| ----------------- mutable borrow occurs here
12 | output_message = message;
| -------------- previous borrow occurs due to use of `output_message` in closure
...
18 | assert_eq!("blah", output_message);
| ^^^^^^^^^^^^^^ immutable borrow occurs here
19 | }
| - mutable borrow ends here
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?