其他資源
整合測試
如果您要以用戶端身分測試程式庫,請採用整合測試。
在 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時會一併執行這些程式碼。 - 程式碼中新增
#後,即可從文件中隱藏,但仍會編譯/執行。 - 請在 Rust Playground 上測試上述程式碼。