2017-09-23 25 views
0

我有一個測試潛水前初始化變量到測試的細節,我想使用相同的變量進行第二次測試,而不是重複的初始化代碼:如何在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)可能會做出正確的結果,除了靜態/常量變量的初始化表達式不能太複雜。

我見過lazy_static,但還沒有看到它在測試中使用的任何示例。在看到編譯器錯誤之後,「外部程序包加載宏必須在箱子根目錄下」,在線搜索告訴我有關於在main()之外的內容,但是測試沒有main函數。

在Java中,我將定義該變量,然後在setup()方法中初始化該變量,但我看不到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 
} 

,但還沒有看到的[懶惰靜態]使用任何實例測試

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

#[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 
} 
相關問題