Created
April 10, 2022 20:32
-
-
Save Mart-Bogdan/b8ac4e089abfd7b64c52e37a8832fec1 to your computer and use it in GitHub Desktop.
Snippet to run SetUp/TeadDown in Rust Unit Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative way:
Can be wrapped in macros I guess