如何在Rust测试中为所有测试函数创建具有范围/生命周期的变量?

时间:2017-09-23 10:33:58

标签: unit-testing rust

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

#[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)可能会使其正常,但初始化表达式除外static / const vars不能太复杂。

我已经看过lazy_static,但没有看到任何在测试中使用它的例子。在看到#34的编译器错误之后,一个extern crate加载宏必须位于crate root",在线搜索告诉我是关于在main()之外的事情,但测试没有main函数。

在Java中,我将定义变量,然后在setup()方法中初始化它,但我无法在线查看Rust的示例。

1 个答案:

答案 0 :(得分:2)

最重要的是,请记住Rust测试是在 parallel 中运行的。这意味着任何共享设置都需要是线程安全的。

  

并且不重复初始化代码

你这样做可以避免重复任何其他代码:创建函数,创建类型,创建特征等等:

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
}

另见:

非常特别针对您的情况,由于字符串切片实现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
}