【问题标题】:How to make a variable with a scope/lifecycle for all test functions in a Rust test?如何为 Rust 测试中的所有测试函数创建一个范围/生命周期的变量?
【发布时间】:2017-09-23 10:33:57
【问题描述】:

我有一个测试,它在深入研究测试细节之前初始化一个变量,我想用相同的变量进行第二次测试,而不是重复初始化代码:

#[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
}

我不认为 staticconst 会这样做,因为事先不会知道大小,尽管 PathBuf.from(path) 可能会这样做,除了静态/常量变量的初始化表达式不能太复杂.

我见过lazy_static,但没有见过任何在测试中使用它的例子。这是在看到编译器错误“extern crate loading macros must be at the crate root”之后,在线搜索告诉我这是在main()之外,但测试没有main函数。

在 Java 中,我会定义变量,然后在 setup() 方法中对其进行初始化,但我无法在网上看到 Rust 的示例。

【问题讨论】:

标签: unit-testing rust


【解决方案1】:

首先,请记住,Rust 测试是并行运行的。这意味着任何共享设置都需要是线程安全的。

不要重复初始化代码

您的操作方式与避免重复任何其他代码的方式相同:创建函数、创建类型、创建特征等:

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
}

在 Java 中我会定义变量,然后在 setup() 方法中初始化它

相反,创建一个名为 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
}

但没有看到在测试中使用 [lazy-static] 的任何示例

那是因为在测试中没有不同的使用方式,它只是代码:

#[macro_use]
extern crate lazy_static;

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
}

另见:


非常适合您的情况,因为字符串切片实现了AsRef<Path>,所以您很少需要完全使用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
}

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 2012-06-23
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多