Trying to utilize TDD for Printing Text

Hello Rust Folks,

I'm trying to create a task app, and i am trying to Utilize Test Drive Development (TDD) to make sure the work is stable.

With that in mind, i'm trying to print out the list of tasks (which are being kept in a vector of tasks) and reading them one by one to print out the list of tasks.

pub struct TaskList{
tasks: Vec<Task>
}

#[derive(PartialEq)]
pub struct Task {
    name: String,
    completed: bool,
    priority: u8, //will be 1-5, 1 being highest
}

impl TaskList{
    pub fn create_task(&mut self){
        let new_task = Task {
            name: String::from("Test Task"),
            completed: false,
            priority: 5,
        };
        self.tasks.push(new_task);
    }
    pub fn print_task_list(self, mut writer: impl std::io::Write) -> 
        std::result::Result<(), std::io::Error>{
        for task in self.tasks{
            writeln!(writer, "{name}, {priority}, {completed}",
                     name = task.name,
                     priority = task.priority,
                     completed = task.completed)?; 
        }
    }
}

...

 #[test]
    fn task_print_test(){
    let mut test_task_list = TaskList{tasks: vec![]}; 
    test_task_list.create_task();
    let mut result = Vec::new();
    test_task_list.print_task_list(&mut result);
    assert_eq!(result, b"index, taskname, priority, complete")
    }

i can't get writeln to work. i'm trying to just print to stdout, while still being able to automatically test it in the test file, i try doing that by using Writeln! instead of println to save it to a variable during the test.

End function with return of Ok(())
assert_eq can use slices eg append [..]

The printing seems to work fine in the playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5b7b7729ef1952356df0a3ef5aedba86

1 Like

Pretty sure test output is captured. You can pass the test harness a flag to suppress this:

cargo test -- --nocapture

Can you explain what you mean by "can't get writeln to work"?

Saying something "doesn't work" doesn't give us much direction in the troubleshooting process. As a bonus, forcing yourself to sit down and concisely explain what is going on will often point you towards the solution.

Common examples are

  • a copy of the compilation error
  • the expected output versus the actual output
  • test output mentioning the assertion that failed (it usually says what you expected and what result actually contained)
1 Like