I have a Rust app (a simple interpreter) that needs some setup (initialize a repo) before the environment is usable.
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.
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?
Ignoring Some Tests Unless Specifically Requested If you want to run all tests whether they're ignored or not, you can run cargo test -- --include-ignored .
The #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test , not when you run cargo build .
At its simplest, a test in Rust is a function that's annotated with the test attribute. Attributes are metadata about pieces of Rust code; one example is the derive attribute we used with structs in Chapter 5. To change a function into a test function, add #[test] on the line before fn .
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 }); }
If you use the ctor crate, you can take advantage of a global constructor function that will run before any of your tests are run.
Here's an example initialising the popular env_logger crate (assuming you have added ctor
to your [dev-dependencies]
section in your Cargo.toml
file):
#[cfg(test)]
#[ctor::ctor]
fn init() {
env_logger::init();
}
The function name is unimportant and you may name it anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With