Skip to content

Instantly share code, notes, and snippets.

@Mart-Bogdan
Created April 10, 2022 20:32
Show Gist options
  • Save Mart-Bogdan/b8ac4e089abfd7b64c52e37a8832fec1 to your computer and use it in GitHub Desktop.
Save Mart-Bogdan/b8ac4e089abfd7b64c52e37a8832fec1 to your computer and use it in GitHub Desktop.
Snippet to run SetUp/TeadDown in Rust Unit Tests
// Kudos Eric Opines https://medium.com/@ericdreichert/test-setup-and-teardown-in-rust-without-a-framework-ba32d97aa5ab
// This is bit modified post from his blog post.
#[cfg(test)]
mod tests {
use std::fs::read_dir;
use std::panic;
#[test]
fn it_works() {
run_test(|| {
assert_eq!(2 + 2, 5);
});
}
fn setup(){
}
fn teardown(){
println!("Teardwon!")
}
fn run_test<T>(test: T) -> ()
where T: FnOnce() -> () + panic::UnwindSafe
{
setup();
let result = panic::catch_unwind(|| {
test()
});
teardown();
if let Err(err) = result {
panic::resume_unwind(err);
}
}
}
@Mart-Bogdan
Copy link
Author

Mart-Bogdan commented Apr 10, 2022

Alternative way:

    #[test]
    fn it_works() {
        struct MyGuard{};
        impl Drop for MyGuard{
            fn drop(&mut self) {
                println!("Teardwon!")
            }
        }
        let _guard = MyGuard { }; // must not be just `_`  otherwise would be dropped immediately

        assert_eq!(2 + 2, 5);
    }

Can be wrapped in macros I guess

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment