我希望在我的测试用例中模拟出现在另一个目录中的用户.我在项目根中有几个 case .
| examples/
| | test1_dir/
| | test2_dir/
| src/
| |- main.rs
| |- lib.rs
| |- config.rs
|- Cargo.toml
|- Cargo.lock
在config.rs
内部,有两个测试用例,如下所示:
#[test]
fn config_find_file() {
let original_dir = env::current_dir().unwrap();
env::set_current_dir("examples/test1_dir").unwrap();
// ...
env::set_current_dir(original_dir);
}
#[test]
fn config_find_file_2() {
let original_dir = env::current_dir().unwrap();
env::set_current_dir("examples/test2_dir").unwrap();
// ...
env::set_current_dir(original_dir);
}
当我简单地用cargo test
执行时,50%的时间都失败了.这是因为有时铁 rust 进入竞争状态并试图定位examples/test1_dir/examples/test2_dir
.为了让它通过,我必须跑cargo test -- --test-threads=1
.然而,我在这个项目中有多个测试,我不希望为所有这些测试运行一个线程.以下是我try 过的一些方法:
- Using Absolute Paths-尽管在try 查找要在其中的正确目录时这不会造成任何错误,但当出现在错误的目录中时,线程在测试中途切换环境文件夹并断言条件.
-
Trying to tag tests-我可以跑
cargo test --lib config -- --test-threads=1
分.但是我不可能执行所有其他测试but配置测试,导致我定义的每个库都有过多的测试命令.
我应该如何处理这个问题?