TDDとは何か
TDD(Test-Driven Development:テスト駆動開発)は、実装コードより先にテストを書く開発手法です。「Red→Green→Refactor」のサイクルを短く回すことで、設計品質とコード品質を同時に高めます。
TDDの3ステップサイクル
1. Red → 失敗するテストを書く
2. Green → テストが通る最小の実装をする
3. Refactor → 動くコードをきれいにする
実践例:電卓クラスをTDDで作る
Step 1: 失敗するテストを書く
# test_calculator.py
import pytest
from calculator import Calculator
def test_add_two_numbers():
calc = Calculator()
assert calc.add(2, 3) == 5
def test_add_negative_numbers():
calc = Calculator()
assert calc.add(-1, -2) == -3
pytest # → FAILED(まだ実装がないので当然)
Step 2: 最小の実装
# calculator.py
class Calculator:
def add(self, a: float, b: float) -> float:
return a + b
pytest # → PASSED
Step 3: リファクタリング
この例ではすでにシンプルなので不要。より複雑な機能でリファクタリングが活きます。
pytestの基本
import pytest
# フィクスチャ:テスト前後の共通処理
@pytest.fixture
def calculator():
return Calculator()
def test_divide(calculator):
assert calculator.divide(10, 2) == 5
def test_divide_by_zero(calculator):
with pytest.raises(ZeroDivisionError):
calculator.divide(10, 0)
# パラメータ化テスト
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
])
def test_add_parametrized(calculator, a, b, expected):
assert calculator.add(a, b) == expected
カバレッジ計測
pytest --cov=src --cov-report=html
目標は80%以上のカバレッジです。100%を目指すのは費用対効果が低いことが多いです。
TDDを続けるコツ
- テストは実装と同じリポジトリで管理する
- テストは文書でもある(テスト名で振る舞いを表現)
- 「あとでテストを書く」は幻想——先に書く習慣を
TDDは最初は遅く感じますが、慣れると設計の改善スピードが上がり、結果的に開発が速くなります。





