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

发布于 2025-01-15 10:46:19 字数 168 浏览 2 评论 0 原文

我已经编写了一个网络服务器,需要一些复杂的设置和拆卸,并且正在尝试编写单元测试。 Axum 确实提供了使用 Tower OneShot 功能的示例,但这些示例并不容易实现完整的设置流程。我将如何运行完整的服务器,然后运行附加代码以通过 cargo test 对其进行测试(使用 reqwest)?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

朕就是辣么酷 2025-01-22 10:46:19

CLI 书展示了一个很好的方法:

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

然后你可以编写一个测试像这样:

// 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(())
}

主要本质是这个 Command::cargo_bin("your-binary-name")?

记录在 assert_cmd crate 中,

它允许您从测试中调用二进制文件,而无需先编译它,cargo 会处理它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文