Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way of cleaning up after a unit test in Rust?

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.

like image 365
PureW Avatar asked Jul 07 '16 18:07

PureW


1 Answers

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
like image 172
Shepmaster Avatar answered Oct 11 '22 18:10

Shepmaster