如何在文档测试中构建代码而不是 运行 它?

How do I build code in a documentation test but not run it?

我的文档中的代码只能是 运行 如果用户的机器上有某些软件。为了模拟这一点,我将 panic! 添加到示例代码中:

//!```rust
//!fn main() {
//!    panic!("Not run me");
//!}
//!```

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}

我想查看注释中的代码是否可以编译,但我不想cargo test期间是运行。现在,我得到:

running 1 test
test src/lib.rs -  (line 1) ... FAILED

failures:

---- src/lib.rs -  (line 1) stdout ----
        thread 'rustc' panicked at 'test executable failed:

thread 'main' panicked at 'Not run me', <anon>:2
note: Run with `RUST_BACKTRACE=1` for a backtrace.

I read about doctest = false,但这不仅会禁用注释中代码的 运行ning,还会禁用注释中代码的语法检查。

如何只禁用运行注释中的代码,但在cargo test期间仍然启用注释中的代码编译?

您可以使用多种注释来更改 Rust 代码的处理方式。参见 the test documentation

在你的情况下,听起来 no_run 是你想要的

//!```rust,no_run
//!fn main() {
//!    panic!("Not run me");
//!}
//!```

或者你可以使用 should_panic 这样 Rust 将 运行 代码,但是 预期 恐慌。如果它是无法实际编译的代码,您可以使用 ignore.