0

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?

Jim
  • 3,821
  • 1
  • 28
  • 60

1 Answers1

0

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.

drewtato
  • 6,783
  • 1
  • 12
  • 17
  • I don't think this addresses my question at all... does solution mock the `println!` macro? – Jim Mar 20 '23 at 15:40
  • This was mostly an answer to "Is there any way assert that "Hello, world!" is written to the console". You can't really mock things in rust, especially when you're relying on a predetermined source. Only thing I can think of is replacing `std` with a custom one, which is quite complex. – drewtato Mar 20 '23 at 18:53
  • Ahh I see now. I think this is a nice example of an integration tests that verifies the correct thing is displayed… I have also heard people say “you should not mock what you don’t own” referring to third party things that you didn’t write so maybe there is no unit test for this purely external code wrapper that makes sense…. – Jim Mar 22 '23 at 02:07