我有一个在深入测试细节之前初始化变量的测试,我想用相同的变量进行第二次测试,而不是复制初始化代码:
#[test]
fn test_one() {
let root = Path::new("data/");
// the rest of the test
}
#[test]
fn test_two() {
let root = Path::new("data/");
// the rest of the test
}
我不认为 static
或 const
会这样做,因为大小不会预先知道,尽管 PathBuf.from(path)
可能会成功,除了静态/常量变量的初始化表达式不能太复杂。
我看过 lazy_static ,但还没有看到它在测试中的任何使用示例。这是在看到编译器错误“外部 crate 加载宏必须位于 crate 根”之后,在线搜索告诉我这是在 main()
之外,但测试没有 主要
功能。
在 Java 中,我会定义变量,然后在 setup()
方法中对其进行初始化,但我看不到 Rust 在线示例。
最佳答案
最重要的是,请记住 Rust 测试是并行运行的。这意味着任何共享设置都需要是线程安全的。
and not duplicate the initialization code
您可以按照避免重复任何其他代码的方式来执行此操作:创建函数、创建类型、创建特征等:
use std::path::PathBuf;
fn root() -> PathBuf {
PathBuf::from("data/")
}
#[test]
fn test_one() {
let root = root();
// the rest of the test
}
#[test]
fn test_two() {
let root = root();
// the rest of the test
}
In Java I would define the variable, then initialize it in a
setup()
method
相反,创建一个名为 Setup
的结构包含所有这些变量并将其构造为每个测试中的第一件事:
use std::path::{Path, PathBuf};
struct Setup {
root: PathBuf,
}
impl Setup {
fn new() -> Self {
Self {
root: PathBuf::from("data/"),
}
}
}
#[test]
fn test_one() {
let setup = Setup::new();
let root: &Path = &setup.root;
// the rest of the test
}
#[test]
fn test_two() {
let setup = Setup::new();
let root: &Path = &setup.root;
// the rest of the test
}
but have not seen any examples of [lazy-static] use in tests
那是因为在测试中没有不同的使用方式,它只是代码:
use lazy_static::lazy_static; // 1.4.0
use std::path::Path;
lazy_static! {
static ref ROOT: &'static Path = Path::new("data/");
}
#[test]
fn test_one() {
let root = *ROOT;
// the rest of the test
}
#[test]
fn test_two() {
let root = *ROOT;
// the rest of the test
}
另见:
非常适合您的情况,您很少需要恰好 Path
, 因为字符串切片实现了 AsRef<Path>
.换句话说,大多数接受 Path
的地方接受 &str
:
static ROOT: &str = "data/";
#[test]
fn test_one() {
let root = ROOT;
// the rest of the test
}
#[test]
fn test_two() {
let root = ROOT;
// the rest of the test
}
关于unit-testing - 如何为 Rust 测试中的所有测试函数创建一个具有作用域/生命周期的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378637/