Rust testing setup and teardown fixtures


We can create setup/teardown fixtures using a struct and the Drop trait that will be executed even if the test panics.


examples/testing/fixtures/src/lib.rs
pub fn div(left: u64, right: u64) -> u64 {
    left / right
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Thing {
        name: String,
    }

    impl Thing {
        pub fn new(name: &str) -> Self {
            println!("before {name}");
            Self {
                name: name.to_owned(),
            }
        }
    }

    impl Drop for Thing {
        fn drop(&mut self) {
            println!("after  {}", self.name);
        }
    }

    #[test]
    fn works_2_2() {
        let _thing = Thing::new("2_2");
        let result = div(2, 2);
        assert_eq!(result, 1);
    }

    #[test]
    fn works_2_0() {
        let _thing = Thing::new("2_0");
        let result = div(2, 0);
        assert_eq!(result, 1);
    }

    #[test]
    fn works_4_3() {
        let _thing = Thing::new("4_3");
        let result = div(4, 3);
        assert_eq!(result, 1);
    }
}


running 3 tests
before 2_2
after  2_2
test tests::works_2_2 ... ok
before 2_0
before 4_3
after  4_3
test tests::works_4_3 ... ok
after  2_0
test tests::works_2_0 ... FAILED

failures:

failures:
    tests::works_2_0

test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s