如何在 Rust 中运行任何测试之前运行设置代码? [英] How to run setup code before any tests run in Rust?
问题描述
我有一个 Rust 应用程序(一个简单的解释器),需要在环境可用之前进行一些设置(初始化存储库).
I have a Rust app (a simple interpreter) that needs some setup (initialize a repo) before the environment is usable.
我知道 Rust 以多线程方式运行它的测试(通过货物测试),所以我需要在任何测试运行之前初始化 repo.我也需要每次运行只执行一次,而不是在每次测试之前.
I understand that Rust runs its tests (via cargo test) in a multithreaded manner, so I need to initialize the repo before any tests run. I also need to do this only once per run, not before each test.
在 Java 的 JUnit 中,这将通过 @BeforeClass(或 JUnit 5 中的 @BeforeAll)方法完成.如何在 Rust 中实现同样的功能?
In Java's JUnit this would be done with a @BeforeClass (or @BeforeAll in JUnit 5) method. How can I acheive the same thing in Rust?
推荐答案
没有内置的东西可以做到这一点,但这应该会有所帮助(您需要在开始时调用 initialize()
每次测试):
There's nothing built-in that would do this but this should help (you will need to call initialize()
in the beginning of every test):
use std::sync::Once;
static INIT: Once = Once::new();
pub fn initialize() {
INIT.call_once(|| {
// initialization code here
});
}
这篇关于如何在 Rust 中运行任何测试之前运行设置代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!