为什么不 println!在 Rust 单元测试中工作? [英] Why doesn't println! work in Rust unit tests?

查看:43
本文介绍了为什么不 println!在 Rust 单元测试中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've implemented the following method and unit test:

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);
}

我以这种方式运行单元测试:

I run the unit test this way:

rustc --test app.rs; ./app

我也可以用

cargo test

我收到一条消息,说测试通过了,但 println! 从未显示在屏幕上.为什么不呢?

I get a message back saying the test passed but the println! is never displayed on screen. Why not?

推荐答案

发生这种情况是因为 Rust 测试程序隐藏了成功测试的标准输出,以便测试输出整洁.您可以通过将 --nocapture 选项传递给测试二进制文件或 cargo test 来禁用此行为:

This happens because Rust test programs hide the stdout of successful tests in order for the test output to be tidy. You can disable this behavior by passing the --nocapture option to the test binary or to cargo test:

#[test]
fn test() {
    println!("Hidden output")
}

调用测试:

% rustc --test main.rs; ./main

running 1 test
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

% ./main --nocapture

running 1 test
Hidden output
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

% cargo test -- --nocapture

running 1 test
Hidden output
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

但是,如果测试失败,无论此选项是否存在,都将打印其标准输出.

If tests fail, however, their stdout will be printed regardless if this option is present or not.

这篇关于为什么不 println!在 Rust 单元测试中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆