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

标签 unit-testing rust

由于测试函数在失败时中止,因此不能简单地在被测函数结束时进行清理。

在其他语言的测试框架中,通常有一种方法可以设置回调,在每个测试函数结束时处理清理。

最佳答案

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/

相关文章:

linux - 如何调试 tokio 任务挂起的位置?

c# - 单元测试 - 多次运行的最佳实践

javascript - 在 AngularJS 中模拟 Controller 单元测试的依赖服务

c# - Azure AD B2C 以编程方式获取 token 以进行单元测试

linux - 如何使用unix在数据库中登录和执行命令?

unit-testing - karma + Jasmine ,ReferenceError : browser is not defined

rust - 为什么不能在同一结构中存储值和对该值的引用?

generics - 带有通用参数的 to_string

rust - 为什么在 Rust 中将结构传递给函数会永久地将其移动到该函数?

arrays - 如何遍历整数数组?