Attribute Macro before_each

Source
#[before_each]
Expand description

Will run the code in the matching before_each function at the beginning of every test. Useful to reset state to ensure that a test has a clean slate.

#[cfg(test)]
use test_env_helpers::*;

#[before_each]
#[cfg(test)]
mod my_tests{
    fn before_each(){println!("I get run at the very beginning of every test")}
    #[test]
    fn test_1(){}
    #[test]
    fn test_2(){}
    #[test]
    fn test_3(){}
}

Can be used to reduce the amount of boilerplate setup code that needs to be copied into each test. For example, if you need to ensure that tests in a single test suite are not run in parallel, this can easily be done with a Mutex. However, remembering to copy and paste the code to acquire a lock on the Mutex in every test is tedious and error prone.

#[cfg(test)]
mod without_before_each{
    lazy_static! {
        static ref MTX: Mutex<()> = Mutex::new(());
    }
    #[test]
    fn test_1(){let _m = MTX.lock();}
    #[test]
    fn test_2(){let _m = MTX.lock();}
    #[test]
    fn test_3(){let _m = MTX.lock();}
}

Using before_each removes the need to copy and paste so much and makes making changes easier because they only need to be made in a single location instead of once for every test.

#[cfg(test)]
use test_env_helpers::*;

#[before_each]
#[cfg(test)]
mod with_before_each{
    lazy_static! {
        static ref MTX: Mutex<()> = Mutex::new(());
    }
    fn before_each(){let _m = MTX.lock();}
    #[test]
    fn test_1(){}
    #[test]
    fn test_2(){}
    #[test]
    fn test_3(){}
}