在Rust中进行单元测试后清理的好方法是什么?

Pur*_*reW 8 unit-testing rust

由于测试功能在故障时中止,因此不能简单地在被测功能结束时进行清理.

从其他语言的测试框架来看,通常有一种方法可以设置一个回调来处理每个测试函数末尾的清理.

She*_*ter 8

由于测试功能在故障时中止,因此不能简单地在被测功能结束时进行清理.

使用RAII并实施Drop.它不需要调用任何东西:

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...!");
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法既能做到这一点又不污染源头呢?有没有适合这个的框架? (7认同)
  • @VladyVeselinov 您在测试函数中声明了结构和实现。 (3认同)
  • @VladyVeselinov 看看 https://crates.io/search?q=scope%20guard 并选择一个适合您需求的。 (2认同)