testing - 为集成测试和基准测试共享实用程序函数的惯用方法是什么?

标签 testing rust benchmarking rust-cargo

我的 Rust 项目包含集成测试(在 /tests 目录中)和基准测试(在 /benches 目录中)。我在测试和工作台中需要一些实用函数,但它们与我的 crate 本身无关,所以我不能只将它们放在 /utils 目录中。

处理这种情况的惯用方法是什么?

最佳答案

创建共享箱(首选)

如评论中所述,创建一个新的箱子。您不必将 crate 发布到 crates.io。就keep it as a local unpublished crate在您的项目中并将其标记为 development-only dependency .

这最好与 version 2 of the Cargo resolver 一起使用.为了获得更好的性能,请考虑使用 Cargo workspace .

.
├── Cargo.toml
├── src
│   └── lib.rs
├── tests
│   └── integration.rs
└── utilities
    ├── Cargo.toml
    └── src
        └── lib.rs

Cargo.toml

# ...

[dev-dependencies]
utilities = { path = "utilities" }

utilities/src/lib.rs

pub fn shared_code() {
    println!("I am shared code");
}

tests/integration.rs

extern crate utilities;

#[test]
fn a_test() {
    utilities::shared_code();
}

仅测试模块

您可以将一个模块放入您的 crate 中,该模块仅在通过特定功能时才编译。这与用于单元测试的概念相同。这样做的好处是它可以访问您的库代码的内部结构。它的缺点是每次运行代码时都需要传递标志。

这最好与 version 2 of the Cargo resolver 一起使用.

Cargo.toml

# ...

[features]
test-utilities = []

src/lib.rs

#[cfg(feature = "test-utilities")]
pub mod test_utilities {
    pub fn shared_code() {
        println!("I'm inside the library")
    }
}

tests/integration.rs

extern crate the_library;

#[test]
fn a_test() {
    the_library::test_utilities::shared_code();
}

执行

cargo test --features=test-utilities

这最好与 version 2 of the Cargo resolver 一起使用.

使用来自任意文件路径的模块

这对我来说太丑了,而且真的不正常。

utilities.rs

pub fn shared_code() {
    println!("This is just sitting out there");
}

tests/integration.rs

#[path = "../utilities.rs"]
mod utilities;

#[test]
fn a_test() {
    utilities::shared_code();
}

另见:

关于testing - 为集成测试和基准测试共享实用程序函数的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685024/

相关文章:

unit-testing - 编写集成测试时如何访问主包中的函数?

syntax - 无法从 SPRS 库中初始化 TriMat 矩阵

language-agnostic - 应该使用哪个指标作为基准?

Linux 基准测试工具

php - 贝哈特和水貂 : Use the test environment

ruby - 如何快速测试 ruby​​ 中的类行为

C# API POST 请求

rust - 使用 if let 时如何指定无法推断的类型?

rust - 为什么不可能取消引用装箱的迭代器特征对象?

Hadoop 基准测试/性能测试