其他类型的测试

集成测试

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

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

1. // tests/my_library.rs
2. use my_library::init;

4. #[test]
5. fn test_init() {
6. assert!(init().is_ok());
7. }

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

文档测试

Rust 本身就支持文档测试:

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