valkyrie_pilot
valkyrie_pilot

Reputation: 196

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?

Upvotes: 5

Views: 3975

Answers (2)

5422m4n
5422m4n

Reputation: 950

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.

Upvotes: 7

David Pedersen
David Pedersen

Reputation: 467

See the_real_deal in this example https://github.com/tokio-rs/axum/blob/main/examples/testing/src/main.rs

Upvotes: 2

Related Questions