Is It Possible To Mock Println! In Rust?

209 Views Asked by At

This is kind of a contrived example that no one probably would do in "real life coding", but I am trying to make a test for the default rust code created by cargo new which is this:

fn main() {
    println!("Hello, world!");
}

Is there any way assert that "Hello, world!" is written to the console, possibly by mocking the println! macro?

1

There are 1 best solutions below

3
drewtato On

This is how I would test that (playground)

#[test]
fn test_hello_world() {
    use std::process::Command;

    let status = Command::new("cargo").args(["new", "test-hello-world"]).status().unwrap();
    assert!(status.success());

    let output = Command::new("cargo").current_dir("test-hello-world").args(["run"]).output().unwrap().stdout;
    assert_eq!(output, b"Hello, world!\n".to_vec());

    std::fs::remove_dir_all("test-hello-world").unwrap();
}

This creates the default cargo project and runs it.