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

后端 未结 5 840
天涯浪人
天涯浪人 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条回答
  •  余生分开走
    2020-11-30 18:10

    While testing, standard output is not displayed. Don't use text messages for testing but assert!, assert_eq!, and fail! instead. Rust's unit test system can understand these but not text messages.

    The test you have written will pass even if something goes wrong. Let's see why:

    read_to_end's signature is fn read_to_end(&mut self) -> IoResult>

    It returns an IoResult to indicate success or error. This is just a type def for a Result whose error value is an IoError. It's up to you to decide how an error should be handled. In this case, we want the task to fail, which is done by calling unwrap on the Result.

    This will work:

    let contents = File::open(&Path::new("message.txt"))
        .read_to_end()
        .unwrap();
    

    unwrap should not be overused though.

提交回复
热议问题