我已经实现了以下方法和单元测试:
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
fn read_file(path: &Path) {
let mut file = File::open(path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
println!("{}", contents);
}
#[test]
fn test_read_file() {
let path = &Path::new("/etc/hosts");
println!("{:?}", path);
read_file(path);
}
Run Code Online (Sandbox Code Playgroud)
我以这种方式运行单元测试:
rustc --test app.rs; ./app
Run Code Online (Sandbox Code Playgroud)
我也可以运行它
cargo test
Run Code Online (Sandbox Code Playgroud)
我收到一条消息说测试已通过,但println!屏幕上从未显示过.为什么不?
鉴于以下功能:
freopen("file.txt","w",stdout);
Run Code Online (Sandbox Code Playgroud)
将stdout重定向到一个文件,如何将它重新定向到控制台?
我会注意到,是的还有其他类似的问题,但它们是关于linux/posix的.我正在使用Windows.
您无法分配给stdout,这会使依赖它的一组解决方案无效.dup和dup2()不是Windows的原生,使另一组无效.如上所述,posix函数不适用(除非你计算fdopen()).
我想编写一个提示函数,将传入的字符串发送到stdout,然后返回它从stdin读取的字符串.我怎么测试呢?
以下是该功能的示例:
fn prompt(question: String) -> String {
let mut stdin = BufferedReader::new(stdin());
print!("{}", question);
match stdin.read_line() {
Ok(line) => line,
Err(e) => panic!(e),
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试尝试
#[test]
fn try_to_test_stdout() {
let writer: Vec<u8> = vec![];
set_stdout(Box::new(writer));
print!("testing");
// `writer` is now gone, can't check to see if "testing" was sent
}
Run Code Online (Sandbox Code Playgroud)