相关疑难解决方法(0)

为什么不打印!在Rust单元测试中工作?

我已经实现了以下方法和单元测试:

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!屏幕上从未显示过.为什么不?

println rust

237
推荐指数
7
解决办法
4万
查看次数

freopen stdout和控制台

鉴于以下功能:

freopen("file.txt","w",stdout);
Run Code Online (Sandbox Code Playgroud)

将stdout重定向到一个文件,如何将它重新定向到控制台?

我会注意到,是的还有其他类似的问题,它们是关于linux/posix的.我正在使用Windows.

您无法分配给stdout,这会使依赖它的一组解决方案无效.dup和dup2()不是Windows的原生,使另一组无效.如上所述,posix函数不适用(除非你计算fdopen()).

c windows stdout

7
推荐指数
2
解决办法
2万
查看次数

我怎样才能测试stdin和stdout?

我想编写一个提示函数,将传入的字符串发送到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)

testing rust

7
推荐指数
1
解决办法
1786
查看次数

标签 统计

rust ×2

c ×1

println ×1

stdout ×1

testing ×1

windows ×1