29章 xUnitのパターン
テストフレームワーク(xUnit系)はTDDパターンの集合体である
| 分類 | 内容 |
|---|---|
| Fixture | テストの準備 |
| Exercise | 対象の実行 |
| Verify | 結果検証 |
| Teardown | 後処理 |
Canonicalテスト形式
- 1つのテストが必ず守るべき標準構成テンプレ
public function test_xxx()
{
// Fixture(準備)
// Exercise(実行)
// Verify(検証)
// Teardown(後片付け)
}
ポイント
- 読めば意味が即わかる
- 迷わない
- テストの責務が肥大化しない
Fixture(前準備)
代表パターン
| パターン | 内容 |
|---|---|
| Inline Fixture | テスト内で直接 new |
| Fixture Object | 構築専用クラス |
| Setup Method | setUp() で共通化 |
| Factory/Seed | DB fixture |
Exercise(実行)
実行対象は必ず1つ
Exerciseは1テストにつき必ず1アクション
$result = $service->calculate($price);
Verity(検証)
Assert is all you need
主なVerifyパターン
| パターン | 内容 |
|---|---|
| Result Assertion | 戻り値検証 |
| State Verification | 状態変化確認 |
| Interaction Verification | Mockの呼出確認 |
| Exception Expectation | 例外検証 |
Teardown(後片付け)
リソース解放
protected function tearDown(): void
{
parent::tearDown();
Mockery::close();
}
xUnitはフレームワークではなく
テストの書き方パターン集
xUnitパターンとは
- テスト構造の定石
- 失敗しないための設計規約
- TDDの実装手順がそのまま組み込まれている