我想证明我的 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/