21

Since the test-function aborts on a failure, one cannot simply clean up at the end of the function under test.

From testing frameworks in other languages, there's usually a way to setup a callback that handles cleanup at the end of each test-function.

1 Answer 1

21

Since the test-function aborts on a failure, one cannot simply clean up at the end of the function under test.

Use RAII and implement Drop. It removes the need to call anything:

struct Noisy;

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("I'm melting! Meeeelllllttttinnnng!");
    }
}

#[test]
fn always_fails() {
    let my_setup = Noisy;
    assert!(false, "or else...!");
}
running 1 test
test always_fails ... FAILED

failures:

---- always_fails stdout ----
    thread 'always_fails' panicked at 'or else...!', main.rs:12
note: Run with `RUST_BACKTRACE=1` for a backtrace.
I'm melting! Meeeelllllttttinnnng!


failures:
    always_fails

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
5
  • 6
    Is there a way to do this without polluting the source? Are there any frameworks that are good for this? Oct 31, 2020 at 14:46
  • 3
    @VladyVeselinov You declare the struct and impl within the test function.
    – Calmarius
    Apr 26, 2021 at 20:47
  • 2
    @VladyVeselinov have a look at crates.io/search?q=scope%20guard and pick one that suits your needs.
    – bk138
    Jan 3, 2022 at 19:44
  • 1
    How could this be applied for async calls? Mar 22 at 3:30
  • @TamilVendhanKanagarasu unfortunately, "async drop" is a complicated matter. In some cases, you can spin up a lightweight reactor (like one from the futures crate) to perform the async operation.
    – Shepmaster
    Apr 14 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.