# 整合測試

把測試放在專案根目錄的 `tests/` 資料夾，以「外部使用者」的身分呼叫函式庫的公開 API，確認各部分組合起來能正常運作。

## tests/ 目錄

[單元測試](/testing-unit)寫在原始碼旁邊，測單一函式、也能碰私有細節；整合測試（integration test）則站在外面，只能用別人 `use` 得到的東西。兩者互補：

| | 單元測試 | 整合測試 |
| --- | --- | --- |
| 位置 | `src/` 裡的 `#[cfg(test)] mod tests` | `tests/*.rs` |
| 能測什麼 | 公開與私有項目 | 只有公開 API |
| 編譯方式 | 和函式庫一起編譯 | 每個檔案各自是一個獨立的 crate |
| 需要 `#[cfg(test)]` | 需要 | 不需要，Cargo 只在測試時編譯 `tests/` |

### 第一個整合測試

`tests/` 底下每個 `.rs` 檔都會被編譯成一個獨立的測試執行檔。檔案裡用套件名稱 `use` 函式庫，就像依賴一個外部 crate。

目錄結構：

```text
wordcount/
├── Cargo.toml
├── src/
│   └── lib.rs
└── tests/
    └── counting.rs
```

`src/lib.rs`：

```rust
use std::collections::BTreeMap;

pub fn count_words(text: &str) -> BTreeMap<String, usize> {
    let mut counts = BTreeMap::new();
    for word in text.split_whitespace() {
        *counts.entry(normalize(word)).or_insert(0) += 1;
    }
    counts
}

fn normalize(word: &str) -> String {
    word.trim_matches(|c: char| !c.is_alphanumeric())
        .to_lowercase()
}
```

`tests/counting.rs`：

```rust
use wordcount::count_words;

#[test]
fn counts_repeated_words() {
    let counts = count_words("the cat and the hat");
    assert_eq!(counts["the"], 2);
    assert_eq!(counts["cat"], 1);
}

#[test]
fn ignores_case_and_punctuation() {
    let counts = count_words("Rust, rust! RUST.");
    assert_eq!(counts.len(), 1);
    assert_eq!(counts["rust"], 3);
}
```

執行 `cargo test`，輸出：

```text
   Compiling wordcount v0.1.0 (/path/to/wordcount)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.25s
     Running unittests src/lib.rs (target/debug/build/wordcount/47da67109e8938e9/out/wordcount-47da67109e8938e9)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/counting.rs (target/debug/build/wordcount/622f246b72c58949/out/counting-622f246b72c58949)

running 2 tests
test counts_repeated_words ... ok
test ignores_case_and_punctuation ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests wordcount

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```

輸出分成三段：`unittests src/lib.rs`（單元測試）、`tests/counting.rs`（整合測試）、`Doc-tests`（[文件測試](/testing-doc)）。`Compiling` 行實際是專案的絕對路徑，這裡改寫成 `/path/to/wordcount`；`Running` 行的雜湊值與各項耗時會因機器而異；測試平行執行，`... ok` 的順序可能不同。

### 只能使用公開 API

這段無法編譯：`normalize` 沒有 `pub`，整合測試位在函式庫外面，看不到它。

`tests/internals.rs`：

```rust
#[test]
fn normalize_strips_punctuation() {
    assert_eq!(wordcount::normalize("Hi!"), "hi");
}
```

執行 `cargo test --test internals`，輸出：

```text
error[E0603]: function `normalize` is private
  --> tests/internals.rs:3:27
   |
 3 |     assert_eq!(wordcount::normalize("Hi!"), "hi");
   |                           ^^^^^^^^^ private function
   |
note: the function `normalize` is defined here
  --> src/lib.rs:11:1
   |
11 | fn normalize(word: &str) -> String {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

這正是整合測試的價值：它逼你從使用者的角度檢查 API 是否夠用。私有函式交給同檔的單元測試去測，不要為了測試把它改成 `pub`。`--test 檔名` 只編譯並執行 `tests/` 底下的那一個檔案。

## 共用輔助模組

### tests/common/mod.rs

多個測試檔常需要同樣的測試資料或輔助函式。把它們放在 `tests/common/mod.rs`，每個測試檔用 `mod common;` 引入。

為什麼不寫成 `tests/common.rs`？因為 `tests/` 第一層的每個 `.rs` 檔都會被當成一個測試 crate，輸出裡會多出一段沒有任何測試的 `Running tests/common.rs`。放進子目錄的檔案則不會被單獨編譯。

目錄結構：

```text
wordcount/
├── Cargo.toml
├── src/
│   └── lib.rs
└── tests/
    ├── common/
    │   └── mod.rs
    ├── counting.rs
    ├── ranking.rs
    └── sizes.rs
```

`tests/common/mod.rs`：

```rust
pub fn sample_text() -> &'static str {
    "one fish two fish red fish blue fish"
}

pub fn top_word(text: &str) -> (String, usize) {
    let counts = wordcount::count_words(text);
    counts.into_iter().max_by_key(|(_, n)| *n).unwrap()
}
```

`tests/ranking.rs`：

```rust
mod common;

#[test]
fn fish_is_most_common() {
    let (word, n) = common::top_word(common::sample_text());
    assert_eq!(word, "fish");
    assert_eq!(n, 4);
}
```

`tests/sizes.rs`：

```rust
mod common;

use wordcount::count_words;

#[test]
fn sample_has_five_distinct_words() {
    let text = common::sample_text();
    assert_eq!(count_words(text).len(), 5);
    let (_, top) = common::top_word(text);
    assert!(top <= text.split_whitespace().count());
}
```

`src/lib.rs` 與 `tests/counting.rs` 同上一節。執行 `cargo test --tests`（只跑單元與整合測試，略過文件測試），輸出：

```text
   Compiling wordcount v0.1.0 (/path/to/wordcount)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running unittests src/lib.rs (target/debug/build/wordcount/47da67109e8938e9/out/wordcount-47da67109e8938e9)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/counting.rs (target/debug/build/wordcount/622f246b72c58949/out/counting-622f246b72c58949)

running 2 tests
test ignores_case_and_punctuation ... ok
test counts_repeated_words ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/ranking.rs (target/debug/build/wordcount/7dbcb0d1a8924565/out/ranking-7dbcb0d1a8924565)

running 1 test
test fish_is_most_common ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/sizes.rs (target/debug/build/wordcount/735df69356005306/out/sizes-735df69356005306)

running 1 test
test sample_has_five_distinct_words ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```

注意：`common` 會被複製進每個引入它的測試 crate 各編譯一次。某個測試檔只用到其中一部分函式時，編譯器會對那個 crate 發出 `function ... is never used` 的 `dead_code` 警告；上面讓兩個測試檔都用到兩個輔助函式，所以沒有警告。

## binary crate 的測法

### 把邏輯搬進 lib.rs

只有 `src/main.rs` 的 binary crate 沒有函式庫可以 `use`，整合測試寫 `use 套件名::...` 會得到：

```text
error[E0432]: unresolved import `binonly`
 --> tests/t.rs:1:5
  |
1 | use binonly::add;
  |     ^^^^^^^ use of unresolved module or unlinked crate `binonly`
```

慣用做法是把邏輯放進 `src/lib.rs`，`main.rs` 只負責讀參數、呼叫函式庫、印結果（見 [模組系統](/modules-system) 的 lib.rs 與 main.rs 並存）。這樣絕大部分的程式都能被整合測試直接呼叫。

目錄結構：

```text
tally/
├── Cargo.toml
├── src/
│   ├── lib.rs
│   └── main.rs
└── tests/
    ├── cli.rs
    └── logic.rs
```

`src/lib.rs`：

```rust
pub fn summarize(numbers: &[i64]) -> String {
    let sum: i64 = numbers.iter().sum();
    format!("count={} sum={}", numbers.len(), sum)
}

pub fn parse_args(args: &[String]) -> Result<Vec<i64>, String> {
    args.iter()
        .map(|a| a.parse::<i64>().map_err(|_| format!("not a number: {}", a)))
        .collect()
}
```

`src/main.rs`：

```rust
use std::env;
use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = env::args().skip(1).collect();
    match tally::parse_args(&args) {
        Ok(nums) => {
            println!("{}", tally::summarize(&nums));
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: {}", e);
            ExitCode::from(2)
        }
    }
}
```

`tests/logic.rs`：

```rust
use tally::{parse_args, summarize};

#[test]
fn summarizes_numbers() {
    assert_eq!(summarize(&[3, 4, -2]), "count=3 sum=5");
}

#[test]
fn rejects_words() {
    let args = vec!["7".to_string(), "x".to_string()];
    assert_eq!(parse_args(&args), Err("not a number: x".to_string()));
}
```

執行 `cargo test --test logic`，輸出：

```text
   Compiling tally v0.1.0 (/path/to/tally)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.17s
     Running tests/logic.rs (target/debug/build/tally/97a44328733ed5cd/out/logic-97a44328733ed5cd)

running 2 tests
test summarizes_numbers ... ok
test rejects_words ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```

### CARGO_BIN_EXE：執行真正的執行檔

`main.rs` 剩下的部分（參數處理、結束碼、輸出格式）可以直接執行編譯好的程式來測。Cargo 在編譯整合測試時提供 `CARGO_BIN_EXE_<執行檔名稱>` 環境變數（Rust 1.43 起），值是執行檔的路徑；用 `env!` 在編譯期取得，再交給 `std::process::Command` 執行（見 [std::process](/pkg-process)）。

`tests/cli.rs`：

```rust
use std::process::Command;

#[test]
fn prints_summary() {
    let out = Command::new(env!("CARGO_BIN_EXE_tally"))
        .args(["10", "20"])
        .output()
        .unwrap();
    assert!(out.status.success());
    assert_eq!(String::from_utf8_lossy(&out.stdout), "count=2 sum=30\n");
}

#[test]
fn bad_input_exits_with_2() {
    let out = Command::new(env!("CARGO_BIN_EXE_tally"))
        .arg("ten")
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(2));
    assert_eq!(
        String::from_utf8_lossy(&out.stderr),
        "error: not a number: ten\n"
    );
}
```

執行 `cargo test --test cli`，輸出：

```text
   Compiling tally v0.1.0 (/path/to/tally)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running tests/cli.rs (target/debug/build/tally/816a8055e3ae25c8/out/cli-816a8055e3ae25c8)

running 2 tests
test prints_summary ... ok
test bad_input_exits_with_2 ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.23s
```

執行整合測試前，Cargo 會先編譯好 `tally` 執行檔。因為要啟動外部程序，這組測試花了 `0.23s`，比直接呼叫函式慢；耗時依機器而異。

## 重點整理

- `tests/` 下每個 `.rs` 檔是獨立的 crate，用套件名稱 `use` 函式庫，只能碰公開 API
- 私有函式用單元測試測，不要為了整合測試改成 `pub`
- 共用輔助程式放 `tests/common/mod.rs`，各測試檔以 `mod common;` 引入
- `cargo test --test 檔名` 只跑一個整合測試檔，`--tests` 略過文件測試
- binary crate 把邏輯移到 `lib.rs`；要測執行檔本身時用 `env!("CARGO_BIN_EXE_名稱")` 搭配 `Command`

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
