Reputation: 196
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
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
Reputation: 467
See the_real_deal
in this example https://github.com/tokio-rs/axum/blob/main/examples/testing/src/main.rs
Upvotes: 2