简体   繁体   English

你如何运行主要的二进制文件,然后在 Rust 中运行基于它的测试?

[英]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. Axum 确实提供了使用 Tower OneShot 功能的示例,但这些示例并不容易实现完整的设置流程。 How would I run the full server, and then run additional code to test it (using reqwest) with cargo test ?我将如何运行完整的服务器,然后运行额外的代码来测试它(使用 reqwest)与cargo test

The CLI book has a nice approach shown: CLI 书有一个很好的方法显示:

# 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")?主要本质是这个Command::cargo_bin("your-binary-name")?

That is documented in the assert_cmd crate记录在assert_cmd箱中

That allows you to call your binary from a test, without the need to compile it first, cargo takes care of it.这允许您从测试中调用您的二进制文件,而无需先编译它,cargo 会处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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