How to Use Test Fixtures and Setup/Teardown in Rust

Mark test functions with #[test], use #[cfg(test)] for modules, and call shared setup functions from a common module to manage fixtures.

Use the #[test] attribute to mark test functions and the #[cfg(test)] attribute to conditionally compile test modules, while calling setup functions from a shared common module.

#[cfg(test)]
mod tests {
    mod common;

    #[test]
    fn it_adds_two() {
        common::setup();
        let result = add_two(2);
        assert_eq!(result, 4);
    }
}

For teardown logic, use the Drop trait on a struct created in the setup phase to ensure cleanup runs when the test scope ends.