テストコード生成
AIに高品質なテストコードを生成させる方法を学びます。単体テスト、統合テストを効率的に作成しましょう。
テスト生成の依頼方法
効果的なプロンプト
以下の関数のテストを書いてください。
```python
def calculate_discount(price: int, user_type: str) -> int:
if user_type == "premium":
return int(price * 0.8)
elif user_type == "member":
return int(price * 0.9)
return price
```
【テストケース】
1. 正常系: 各ユーザータイプで正しい割引
2. 境界値: price = 0, price = 1
3. 異常系: 無効なユーザータイプ
4. エッジケース: 小数点以下の切り捨て確認
pytest を使用してください。
生成されるテスト例
import pytest
from app.utils import calculate_discount
class TestCalculateDiscount:
def test_premium_user_gets_20_percent_off(self):
assert calculate_discount(1000, "premium") == 800
def test_member_gets_10_percent_off(self):
assert calculate_discount(1000, "member") == 900
def test_regular_user_no_discount(self):
assert calculate_discount(1000, "regular") == 1000
def test_zero_price(self):
assert calculate_discount(0, "premium") == 0
@pytest.mark.parametrize("price,expected", [
(999, 799), # 999 * 0.8 = 799.2 → 799
(1, 0), # 1 * 0.8 = 0.8 → 0
])
def test_decimal_truncation(self, price, expected):
assert calculate_discount(price, "premium") == expected
テストカバレッジの向上
不足テストを洗い出す
以下のコードとテストを見て、 テストされていないケースを指摘してください。 【本体コード】 (コードを貼り付け) 【既存テスト】 (テストを貼り付け) 不足しているテストケースを追加してください。
モックの生成
外部依存のモック
from unittest.mock import Mock, patch
@patch('app.services.email_service.send_email')
def test_user_registration_sends_email(mock_send):
mock_send.return_value = True
result = register_user("test@example.com")
assert result.success
mock_send.assert_called_once_with(
to="test@example.com",
subject="Welcome!"
)
まとめ
- ✓テストケースを明示 - 正常系、異常系、境界値を指定
- ✓parametrize - 複数パターンを効率的にテスト
- ✓モック活用 - 外部依存を分離