unit-testing - 如何编写确保编译错误的测试?

标签 unit-testing testing rust integration-testing

我想证明我的 API 静态地防止了编译失败导致的无效使用。

有工具可确保代码在运行时出现困惑 (#[should_panic]),但我找不到任何关于编译失败的信息。文档测试似乎最有希望,因为每个片段都是一个单独的编译单元,但 panic 检查似乎就是全部。

最佳答案

目前没有一种方法可以表明常规测试不应编译。从相关问题(#521#1994)来看,#[compile_fail] 不太可能在短期内可用。

但是,还有其他两种方法可以编写这些测试。

文档测试

Rust 1.22 ,您可以通过使用 compile_fail 标记代码片段来进行本应无法编译的 doc 测试:

/// Foos a bar.
/// 
/// # Example
///
/// ```compile_fail
/// foo(3); // 3 is not a bar
/// ```
fn foo(bar: Bar) {
}

编译测试工具包

Rust 项目内部使用的编译测试工具被提取到专用 crate 中 compiletest_rs .

使用 documentation 中建议的样板,可以在 tests/compile-fail 文件夹中编写编译失败测试:

fn main() {
   let x: bool = 0;
}

另见:


尽管如此,还是应该谨慎编写这些测试。引用 compile_fail 功能的公告:

Please note that these kinds of tests can be more fragile than others, as additions to Rust may cause code to compile when it previously would not.

关于unit-testing - 如何编写确保编译错误的测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327185/

相关文章:

python - PyO3 中对象向量的垃圾收集

error-handling - 如何追溯错误结果的原因?

javascript - 在 jasmine 中监视 jQuery $ ('...' ) 选择器

单元测试中 ManagedObject 上的 swift 核心数据错误命名空间

objective-c - 使用 Instruments 测试 iOS 应用程序开发的最佳实践

rest - ALM REST 有什么方法可以访问测试参数吗?

ios - 使用 Swift 在 Xcode 中进行异步 UI 测试

javascript - 单元测试:Q.js 和 Jasmine.js

javascript - CasperJS 不评估 jQuery 方法

rust - 如何从结构验证选项参数值