Why doesn't println! work in Rust unit tests?

后端 未结 5 820
天涯浪人
天涯浪人 2020-11-30 17:09

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) {
    l         


        
5条回答
  •  -上瘾入骨i
    2020-11-30 18:04

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

    Invoking tests:

    % 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.

提交回复
热议问题