简体   繁体   中英

How do you run the main binary and then run tests based on it in Rust?

I have written a webserver which requires some complicated setup and teardown, and am trying to write unit tests. Axum does provide examples using the Tower OneShot function, but these don't easily allow the full flow of the setup. How would I run the full server, and then run additional code to test it (using reqwest) with cargo test ?

The CLI book has a nice approach shown:

# add this to your Cargo.toml
[dev-dependencies]
assert_cmd = "2.0"
predicates = "2.1"

Then you can write a test like this:

// tests/cli.rs

use assert_cmd::prelude::*; // Add methods on commands
use predicates::prelude::*; // Used for writing assertions
use std::process::Command; // Run programs

#[test]
fn file_doesnt_exist() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::cargo_bin("your-binary-name")?;

    cmd.arg("foobar").arg("test/file/doesnt/exist");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("could not read file"));

    Ok(())
}

The main essence is this Command::cargo_bin("your-binary-name")?

That is documented in the assert_cmd crate

That allows you to call your binary from a test, without the need to compile it first, cargo takes care of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM