How to Test Command-Line Applications in Rust (assert_cmd)

Test Rust CLI apps by spawning the binary with assert_cmd and asserting exit codes and output.

Use the assert_cmd crate to spawn your binary as a subprocess and assert its exit code, stdout, and stderr.

use assert_cmd::Command;

#[test]
fn test_minigrep() {
    let mut cmd = Command::cargo_bin("minigrep").unwrap();
    cmd.arg("searchstring")
       .arg("example-filename.txt")
       .assert()
       .success()
       .stdout(predicates::str::contains("expected output"));
}

Add assert_cmd = "2.0" and predicates = "3.0" to your Cargo.toml dependencies.