在参数化测试中尝试的方法的问题是
TEST_FILES
仅在运行时计算,而您希望能够在编译时使用它来消除
#[test]
功能。
为了实现这一点,您需要某种方法来计算
TEST\u文件
在编译时。一种可能性是通过一个构建脚本,该脚本在构建时迭代glob并写出
#[测试]
函数添加到可以从测试目录中包含的文件。
在里面
Cargo.toml
:
[package]
# ...
build = "build.rs"
[build-dependencies]
glob = "0.2"
在里面
build.rs
:
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
extern crate glob;
use glob::glob;
fn main() {
let test_files = glob("tests/*.java")
.expect("Failed to read glob pattern")
.into_iter();
let outfile_path = Path::new(&env::var("OUT_DIR").unwrap()).join("gen_tests.rs");
let mut outfile = File::create(outfile_path).unwrap();
for file in test_files {
let java_file = file.unwrap().to_str().unwrap().to_string();
// FIXME: fill these in with your own logic for manipulating the filename.
let name = java_file;
let name1 = "NAME1";
let name2 = "NAME2";
write!(outfile, r#"
#[test]
fn test_globbed_{name}_null() {{
check_files({name1}, {name2}, "null test");
}}
#[test]
fn test_globbed_{name}_non_null() {{
check_files({name1}, {name2}, "non-null test");
}}
"#, name=name, name1=name1, name2=name2).unwrap();
}
}
在里面
tests/tests.rs
:
include!(concat!(env!("OUT_DIR"), "/gen_tests.rs"));