SKILL.md
readonlyread-only
name
rust-testing
description
Rust 測試模式,包含單元測試、整合測試、非同步測試、基於屬性的測試、模擬與覆蓋率。遵循 TDD 方法論。
Rust 測試模式
全面的 Rust 測試模式,幫助你遵循 TDD 方法論撰寫可靠且易於維護的測試。
使用時機
- 撰寫新的 Rust 函式、方法或特徵
- 為現有程式碼增加測試覆蓋率
- 為效能關鍵程式碼建立基準測試
- 為輸入驗證實作基於屬性的測試
- 在 Rust 專案中遵循 TDD 工作流程
運作方式
- 識別目標程式碼 — 找出要測試的函式、特徵或模組
- 撰寫測試 — 在
#[cfg(test)]模組中使用#[test],或使用 rstest 進行參數化測試,或使用 proptest 進行基於屬性的測試 - 模擬相依性 — 使用 mockall 隔離受測單元
- 執行測試(紅燈) — 確認測試因預期錯誤而失敗
- 實作(綠燈) — 撰寫最少程式碼讓測試通過
- 重構 — 在保持測試綠燈的同時改善程式碼
- 檢查覆蓋率 — 使用 cargo-llvm-cov,目標 80% 以上
Rust 的 TDD 工作流程
紅燈-綠燈-重構循環
紅燈 → 先撰寫一個會失敗的測試
綠燈 → 撰寫最少程式碼讓測試通過
重構 → 在保持測試綠燈的同時改善程式碼
重複 → 繼續下一個需求
Rust 中的逐步 TDD
// 紅燈:先寫測試,使用 todo!() 作為佔位符
pub fn add(a: i32, b: i32) -> i32 { todo!() }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() { assert_eq!(add(2, 3), 5); }
}
// cargo test → 在 'not yet implemented' 處 panic
// 綠燈:將 todo!() 替換為最簡實作
pub fn add(a: i32, b: i32) -> i32 { a + b }
// cargo test → 通過,然後在保持測試綠燈的同時重構
單元測試
模組層級的測試組織
// src/user.rs
pub struct User {
pub name: String,
pub email: String,
}
impl User {
pub fn new(name: impl Into<String>, email: impl Into<String>) -> Result<Self, String> {
let email = email.into();
if !email.contains('@') {
return Err(format!("無效的 email: {email}"));
}
Ok(Self { name: name.into(), email })
}
pub fn display_name(&self) -> &str {
&self.name
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn creates_user_with_valid_email() {
let user = User::new("Alice", "alice@example.com").unwrap();
assert_eq!(user.display_name(), "Alice");
assert_eq!(user.email, "alice@example.com");
}
#[test]
fn rejects_invalid_email() {
let result = User::new("Bob", "not-an-email");
assert!(result.is_err());
assert!(result.unwrap_err().contains("無效的 email"));
}
}
斷言巨集
assert_eq!(2 + 2, 4); // 相等
assert_ne!(2 + 2, 5); // 不相等
assert!(vec![1, 2, 3].contains(&2)); // 布林值
assert_eq!(value, 42, "預期 42 但得到 {value}"); // 自訂訊息
assert!((0.1_f64 + 0.2 - 0.3).abs() < f64::EPSILON); // 浮點數比較
錯誤與恐慌測試
測試 Result 回傳值
#[test]
fn parse_returns_error_for_invalid_input() {
let result = parse_config("}{invalid");
assert!(result.is_err());
// 斷言特定的錯誤變體
let err = result.unwrap_err();
assert!(matches!(err, ConfigError::ParseError(_)));
}
#[test]
fn parse_succeeds_for_valid_input() -> Result<(), Box<dyn std::error::Error>> {
let config = parse_config(r#"{"port": 8080}"#)?;
assert_eq!(config.port, 8080);
Ok(()) // 如果任何 ? 回傳 Err,測試就會失敗
}
測試恐慌
#[test]
#[should_panic]
fn panics_on_empty_input() {
process(&[]);
}
#[test]
#[should_panic(expected = "索引超出範圍")]
fn panics_with_specific_message() {
let v: Vec<i32> = vec![];
let _ = v[0];
}
整合測試
檔案結構
my_crate/
├── src/
│ └── lib.rs
├── tests/ # 整合測試
│ ├── api_test.rs # 每個檔案是一個獨立的測試二進位檔
│ ├── db_test.rs
│ └── common/ # 共用的測試工具
│ └── mod.rs
撰寫整合測試
// tests/api_test.rs
use my_crate::{App, Config};
#[test]
fn full_request_lifecycle() {
let config = Config::test_default();
let app = App::new(config);
let response = app.handle_request("/health");
assert_eq!(response.status, 200);
assert_eq!(response.body, "OK");
}
非同步測試
使用 Tokio
#[tokio::test]
async fn fetches_data_successfully() {
let client = TestClient::new().await;
let result = client.get("/data").await;
assert!(result.is_ok());
assert_eq!(result.unwrap().items.len(), 3);
}
#[tokio::test]
async fn handles_timeout() {
use std::time::Duration;
let result = tokio::time::timeout(
Duration::from_millis(100),
slow_operation(),
).await;
assert!(result.is_err(), "應該已經超時");
}
測試組織模式
使用 rstest 進行參數化測試
use rstest::{rstest, fixture};
#[rstest]
#[case("hello", 5)]
#[case("", 0)]
#[case("rust", 4)]
fn test_string_length(#[case] input: &str, #[case] expected: usize) {
assert_eq!(input.len(), expected);
}
// 測試夾具
#[fixture]
fn test_db() -> TestDb {
TestDb::new_in_memory()
}
#[rstest]
fn test_insert(test_db: TestDb) {
test_db.insert("key", "value");
assert_eq!(test_db.get("key"), Some("value".into()));
}
測試輔助函式
#[cfg(test)]
mod tests {
use super::*;
/// 建立一個具有合理預設值的測試使用者。
fn make_user(name: &str) -> User {
User::new(name, &format!("{name}@test.com")).unwrap()
}
#[test]
fn user_display() {
let user = make_user("alice");
assert_eq!(user.display_name(), "alice");
}
}
使用 proptest 進行基於屬性的測試
基本屬性測試
use proptest::prelude::*;
proptest! {
#[test]
fn encode_decode_roundtrip(input in ".*") {
let encoded = encode(&input);
let decoded = decode(&encoded).unwrap();
assert_eq!(input, decoded);
}
#[test]
fn sort_preserves_length(mut vec in prop::collection::vec(any::<i32>(), 0..100)) {
let original_len = vec.len();
vec.sort();
assert_eq!(vec.len(), original_len);
}
#[test]
fn sort_produces_ordered_output(mut vec in prop::collection::vec(any::<i32>(), 0..100)) {
vec.sort();
for window in vec.windows(2) {
assert!(window[0] <= window[1]);
}
}
}
自訂策略
use proptest::prelude::*;
fn valid_email() -> impl Strategy<Value = String> {
("[a-z]{1,10}", "[a-z]{1,5}")
.prop_map(|(user, domain)| format!("{user}@{domain}.com"))
}
proptest! {
#[test]
fn accepts_valid_emails(email in valid_email()) {
assert!(User::new("Test", &email).is_ok());
}
}
使用 mockall 進行模擬
基於特徵的模擬
use mockall::{automock, predicate::eq};
#[automock]
trait UserRepository {
fn find_by_id(&self, id: u64) -> Option<User>;
fn save(&self, user: &User) -> Result<(), StorageError>;
}
#[test]
fn service_returns_user_when_found() {
let mut mock = MockUserRepository::new();
mock.expect_find_by_id()
.with(eq(42))
.times(1)
.returning(|_| Some(User { id: 42, name: "Alice".into() }));
let service = UserService::new(Box::new(mock));
let user = service.get_user(42).unwrap();
assert_eq!(user.name, "Alice");
}
#[test]
fn service_returns_none_when_not_found() {
let mut mock = MockUserRepository::new();
mock.expect_find_by_id()
.returning(|_| None);
let service = UserService::new(Box::new(mock));
assert!(service.get_user(99).is_none());
}
文件測試
可執行的文件
/// 將兩個數字相加。
///
/// # 範例
///
/// ```
/// use my_crate::add;
///
/// assert_eq!(add(2, 3), 5);
/// assert_eq!(add(-1, 1), 0);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// 解析設定字串。
///
/// # 錯誤
///
/// 如果輸入不是有效的 TOML,則回傳 `Err`。
///
/// ```no_run
/// use my_crate::parse_config;
///
/// let config = parse_config(r#"port = 8080"#).unwrap();
/// assert_eq!(config.port, 8080);
/// ```
///
/// ```no_run
/// use my_crate::parse_config;
///
/// assert!(parse_config("}{invalid").is_err());
/// ```
pub fn parse_config(input: &str) -> Result<Config, ParseError> {
todo!()
}
使用 Criterion 進行基準測試
# Cargo.toml
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "benchmark"
harness = false
// benches/benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => n,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fibonacci(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, bench_fibonacci);
criterion_main!(benches);
測試覆蓋率
執行覆蓋率
# 安裝:cargo install cargo-llvm-cov(或在 CI 中使用 taiki-e/install-action)
cargo llvm-cov # 摘要
cargo llvm-cov --html # HTML 報告
cargo llvm-cov --lcov > lcov.info # LCOV 格式用於 CI
cargo llvm-cov --fail-under-lines 80 # 低於門檻則失敗
覆蓋率目標
| 程式碼類型 | 目標 |
|---|---|
| 關鍵商業邏輯 | 100% |
| 公開 API | 90%+ |
| 一般程式碼 | 80%+ |
| 生成程式碼 / FFI 綁定 | 排除 |
測試指令
cargo test # 執行所有測試
cargo test -- --nocapture # 顯示 println 輸出
cargo test test_name # 執行符合模式的名稱測試
cargo test --lib # 僅單元測試
cargo test --test api_test # 僅整合測試
cargo test --doc # 僅文件測試
cargo test --no-fail-fast # 不在第一個失敗時停止
cargo test -- --ignored # 執行被忽略的測試
最佳實務
應該做:
- 先寫測試(TDD)
- 使用
#[cfg(test)]模組進行單元測試 - 測試行為,而非實作
- 使用描述性的測試名稱來說明情境
- 優先使用
assert_eq!而非assert!以獲得更好的錯誤訊息 - 在回傳
Result的測試中使用?以獲得簡潔的錯誤輸出 - 保持測試獨立 — 不要共用可變狀態
不應該做:
- 當可以測試
Result::is_err()時,不要使用#[should_panic] - 不要模擬所有東西 — 可行時優先使用整合測試
- 不要忽略不穩定的測試 — 修復或隔離它們
- 不要在測試中使用
sleep()— 使用通道、屏障或tokio::time::pause() - 不要跳過錯誤路徑測試
CI 整合
# GitHub Actions
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
- name: 檢查格式化
run: cargo fmt --check
- name: Clippy
run: cargo clippy -- -D warnings
- name: 執行測試
run: cargo test
- uses: taiki-e/install-action@cargo-llvm-cov
- name: 覆蓋率
run: cargo llvm-cov --fail-under-lines 80
記住:測試就是文件。它們展示你的程式碼應該如何使用。請清楚撰寫並保持更新。






