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

How do I write a test assuring a compilation error?

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

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

目前没有一种方法可以指示常规测试不应编译。从相关问题 (#521 and #1994 ) 来看,#[compile_fail] 之类的东西不太可能很快可用。

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

文档测试

Rust 1.22 起,您可以通过使用 compile_fail:

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

编译测试工具包

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

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

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

另请参阅:

  • Can I write tests for invalid lifetimes?

尽管如此,还是应该谨慎编写这些测试。引用 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.