由于测试函数在失败时中止,因此不能简单地在被测函数结束时进行清理。
在其他语言的测试框架中,通常有一种方法可以设置回调,在每个测试函数结束时处理清理。
最佳答案
Since the test-function aborts on a failure, one cannot simply clean up at the end of the function under test.
使用 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...!");
}
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
关于unit-testing - 在 Rust 中进行单元测试后清理的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253321/