其他类型的测试

集成测试

如果您想要以客户的身份测试您的库,请使用集成测试。

tests/ 下方创建一个 .rs 文件:

// tests/my_library.rs use my_library::init; #[test] fn test_init() { assert!(init().is_ok()); }

这些测试只能使用您的 crate 的公共 API。

文档测试

Rust 本身就支持文档测试:

#![allow(unused)] fn main() { /// Shortens a string to the given length. /// /// ``` /// # use playground::shorten_string; /// assert_eq!(shorten_string("Hello World", 5), "Hello"); /// assert_eq!(shorten_string("Hello World", 20), "Hello World"); /// ``` pub fn shorten_string(s: &str, length: usize) -> &str { &s[..std::cmp::min(length, s.len())] } }
  • /// 注释中的代码块会自动被视为 Rust 代码。
  • 代码会作为 cargo test 的一部分进行编译和执行。
  • Adding # in the code will hide it from the docs, but will still compile/run it.
  • Rust Playground 上测试上述代码。