gpt4 book ai didi

testing - 如何在不要求参数函数可变的情况下测试元函数?

转载 作者:行者123 更新时间:2023-12-03 11:32:18 25 4
gpt4 key购买 nike

我编写了一个函数save,该函数将一个函数作为参数:

fn save(method:&dyn Fn(&'static str)) {
method("Hello world");
}

fn print(string:&'static str) {
println!("{}", string);
}

fn main() {
save(&print)
}

这很棒!但是我现在要测试 save。我看到的最好的方法是使用 FnMut:

fn save(method: &mut dyn FnMut(&'static str)) {
method("Hello world");
}

fn print(string: &'static str) {
println!("{}", string);
}

fn main() {
save(&mut print)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn save_test() {
let actual = {
let mut actual = String::new();
let mut method = |string: &'static str| {
actual = format!("{}{}", actual, string);
};
save(&mut method);
save(&mut method);
actual
};
let expected = "Hello worldHello world".to_string();

assert_eq!(actual, expected);
}
}

这仍然有效,可以完成我想要的一切!但是现在,每当我保存 call时,我就必须使用可变引用。尽管这不会影响功能,但会混淆代码。有没有更好的方法来达到相同的结果?

最佳答案

您可以使用 RefCell 获得内部可变性,从而允许您通过共享引用来可变变量。非常适合测试以下内容:

#[cfg(test)]
mod tests {
use std::cell::RefCell;
use super::*;

#[test]
fn save_test() {
let actual = {
// wrap "actual" in a RefCell, which allows for interior mutability
let actual = RefCell::new(String::new());
let method = |string: &'static str| {
// mutably borrow the string at runtime
// (can panic in already borrowed, but not a problem here)
let mut actual = actual.borrow_mut();

// append string (equivalent to your format!() but can be more
// efficient)
actual.push_str(string);
};

save(&method);
save(&method);

// move string out of RefCell
actual.into_inner()
};
let expected = "Hello worldHello world".to_string();

assert_eq!(actual, expected);
}
}

Run in Playground

关于testing - 如何在不要求参数函数可变的情况下测试元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60876355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com