TL;DR: 我想实现 trait std::io::Write
,以便于进行单元测试输出到内存缓冲区,最好是 String。
我一定漏掉了某些简单的东西。
与另一个问题类似,在 Rust 中写入文件或标准输出, 我正在处理可以使用任何 std::io::Write
实现的代码。
它操作的结构定义如下:
pub struct MyStructure {
writer: Box<dyn Write>,
}
现在,创建可以写入文件或stdout
的实例变得很容易:
impl MyStructure {
pub fn use_stdout() -> Self {
let writer = Box::new(std::io::stdout());
MyStructure { writer }
}
pub fn use_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let writer = Box::new(File::create(path)?);
Ok(MyStructure { writer })
}
pub fn printit(&mut self) -> Result<()> {
self.writer.write(b"hello")?;
Ok(())
}
}
但是对于单元测试,我还需要一种运行业务逻辑(在这里由方法printit()
表示)并捕获其输出的方式,以便可以在测试中检查其内容。
我无法想出如何实现这一点。 这个示例代码 显示了我想要使用它的方式,但它无法编译,因为它违反了借用规则。
// invalid code - does not compile!
fn main() {
let mut buf = Vec::new(); // This buffer should receive output
let mut x2 = MyStructure { writer: Box::new(buf) };
x2.printit().unwrap();
// now, get the collected output
let output = std::str::from_utf8(buf.as_slice()).unwrap().to_string();
// here I want to analyze the output, for instance in unit-test asserts
println!("Output to string was {}", output);
}
有没有想法如何正确编写代码?即如何在内存结构(String、Vec等)之上实现一个写入器,以便在之后可以访问它?
impl for
语句,您在其中声明已实现了trait,不确定是否需要。 - Simson