簡體   English   中英

如何在Rust測試中為所有測試功能的作用域/生命周期創建變量?

[英]How to make a variable with a scope/lifecycle for all test functions in a Rust test?

我有一個測試,可以在深入測試細節之前初始化變量,並且我想使用相同的變量進行第二次測試,並且不重復初始化代碼:

#[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 ,但是還沒有看到在測試中使用它的任何示例。 在看到編譯器出現錯誤“外部包裝箱加載宏必須位於包裝箱根目錄”之后,在線搜索告訴我這是在main()之外,但是測試沒有main功能。

在Java中,我將定義變量,然后在setup()方法中對其進行初始化,但是我看不到Rust的在線示例。

首先,請記住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
}

但沒有看到測試中使用任何[懶惰-靜態]用法的示例

這是因為在測試中沒有不同的使用方式,它只是代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM