我有一个Rust项目,其中包含集成测试(在/tests
目录中)和基准测试(在/benches
目录中)。我需要在测试和基准中使用一些实用函数,但它们与我的创建本身无关,因此我不能将它们放入/utils
目录中。
如何处理这种情况的惯用方式是什么?
我有一个Rust项目,其中包含集成测试(在/tests
目录中)和基准测试(在/benches
目录中)。我需要在测试和基准中使用一些实用函数,但它们与我的创建本身无关,因此我不能将它们放入/utils
目录中。
如何处理这种情况的惯用方式是什么?
如评论所述,创建一个新的crate。你不必将crate发布到crates.io。只需将其作为本地未发布的crate 保留在项目内,并将其标记为仅用于开发的依赖项。
这最好与Cargo解析器的版本2一起使用。为了获得更好的性能,考虑使用Cargo工作区。
.
├── 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 中,只有当特定功能被传递时才会被编译。这与单元测试使用的概念相同。它的优点是可以访问库代码的内部。缺点是每次运行代码都需要传递标志。
这最好与 Cargo 解析器的第 2 版 一起使用。
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
这种方法让我感到不舒服,而且与常规方式相去甚远。
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();
}
另请参阅:
虽然这对基准测试没有帮助,但我来到这里是为了寻找一种可以在多个集成测试中实现此功能的方法,并且后来发现你可以按照以下集成测试进行:
具有共同代码的模块遵循普通模块规则,因此可以将常见模块创建为 tests/common/mod.rs。
来源:https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html