メインコンテンツにスキップ

🔄 TDD (Test-Driven Development)

📖 TDDとは?

TDDは、最初にテストを書いてから、そのテストに合格するコードを書く開発手法です。バグを減らし、設計を改善することができます!

💡 TDDサイクル

Red-Green-Refactor

1. 🔴 Red: 失敗するテストを書く
2. 🟢 Green: テストに合格する最小限のコードを書く
3. 🔵 Refactor: コードを改善する

🎯 最初のTDD例

電卓を作る

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe

// 1️⃣ Red: 最初にテストを書く
class CalculatorTest : StringSpec({
"2와 3을 더하면 5가 된다" {
val calculator = Calculator()
calculator.add(2, 3) shouldBe 5
}
})

// 컴파일 에러! Calculator가 없음

// 2️⃣ Green: 最小限のコード
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}

// 3️⃣ Refactor: 개선할 부분 없음 (간단하므로)

文字列処理

// 1️⃣ Red: テストを書く
class StringProcessorTest : StringSpec({
"빈 문자열은 빈 문자열을 반환한다" {
val processor = StringProcessor()
processor.reverse("") shouldBe ""
}

"hello를 뒤집으면 olleh가 된다" {
val processor = StringProcessor()
processor.reverse("hello") shouldBe "olleh"
}
})

// 2️⃣ Green: 実装
class StringProcessor {
fun reverse(text: String): String {
return text.reversed()
}
}

// 3️⃣ Refactor: 더 나은 방법이 있을까?
// 이미 간결함!

🎨 実践的なTDD

ショッピングカートの開発

ステップ1: 空のカート

// Red
class ShoppingCartTest : StringSpec({
"새 카트는 아이템이 0개다" {
val cart = ShoppingCart()
cart.getItemCount() shouldBe 0
}
})

// Green
class ShoppingCart {
private val items = mutableListOf<Item>()

fun getItemCount(): Int = items.size
}

data class Item(val name: String, val price: Double)

ステップ2: アイテムを追加

// Red
"아이템을 추가하면 개수가 증가한다" {
val cart = ShoppingCart()
cart.addItem(Item("사과", 1000.0))

cart.getItemCount() shouldBe 1
}

// Green
class ShoppingCart {
private val items = mutableListOf<Item>()

fun addItem(item: Item) {
items.add(item)
}

fun getItemCount(): Int = items.size
}

ステップ3: 合計を計算

// Red
"총액을 계산한다" {
val cart = ShoppingCart()
cart.addItem(Item("사과", 1000.0))
cart.addItem(Item("바나나", 1500.0))

cart.getTotal() shouldBe 2500.0
}

// Green
class ShoppingCart {
private val items = mutableListOf<Item>()

fun addItem(item: Item) {
items.add(item)
}

fun getItemCount(): Int = items.size

fun getTotal(): Double {
return items.sumOf { it.price }
}
}

// Refactor: 깔끔함!

🔥 ビジネスロジックのTDD

割引計算機

// Red: 最初にテスト
class DiscountCalculatorTest : StringSpec({
"10% 할인" {
val calculator = DiscountCalculator()
calculator.calculate(10000.0, 0.1) shouldBe 9000.0
}

"할인율이 0이면 원가" {
val calculator = DiscountCalculator()
calculator.calculate(10000.0, 0.0) shouldBe 10000.0
}

"할인율이 1이면 0원" {
val calculator = DiscountCalculator()
calculator.calculate(10000.0, 1.0) shouldBe 0.0
}
})

// Green: 実装
class DiscountCalculator {
fun calculate(price: Double, rate: Double): Double {
require(rate in 0.0..1.0) { "할인율은 0~1 사이여야 합니다" }
return price * (1 - rate)
}
}

// Refactor: 검증 로직 추가했으므로 테스트 추가
"잘못된 할인율은 예외 발생" {
val calculator = DiscountCalculator()

shouldThrow<IllegalArgumentException> {
calculator.calculate(10000.0, 1.5)
}
}

ユーザー登録

// Red
class UserRegistrationTest : StringSpec({
"유효한 사용자 등록" {
val service = UserRegistration()
val user = service.register("hong@example.com", "Pass123!")

user.email shouldBe "hong@example.com"
}

"중복 이메일은 실패" {
val service = UserRegistration()
service.register("hong@example.com", "Pass123!")

shouldThrow<DuplicateEmailException> {
service.register("hong@example.com", "Pass456!")
}
}

"약한 비밀번호는 실패" {
val service = UserRegistration()

shouldThrow<WeakPasswordException> {
service.register("hong@example.com", "123")
}
}
})

// Green
class UserRegistration {
private val users = mutableMapOf<String, User>()

fun register(email: String, password: String): User {
if (users.containsKey(email)) {
throw DuplicateEmailException()
}

if (password.length < 8) {
throw WeakPasswordException()
}

val user = User(email, password)
users[email] = user
return user
}
}

data class User(val email: String, val password: String)

class DuplicateEmailException : Exception()
class WeakPasswordException : Exception()

// Refactor: 검증 로직 분리
class UserRegistration {
private val users = mutableMapOf<String, User>()
private val validator = UserValidator()

fun register(email: String, password: String): User {
validator.validateEmail(email, users.keys)
validator.validatePassword(password)

val user = User(email, password)
users[email] = user
return user
}
}

class UserValidator {
fun validateEmail(email: String, existingEmails: Set<String>) {
if (existingEmails.contains(email)) {
throw DuplicateEmailException()
}
}

fun validatePassword(password: String) {
if (password.length < 8) {
throw WeakPasswordException()
}
}
}

🎯 TDDのベストプラクティス

小さなステップで

// ❌ 一度に多すぎる
class ComplexTest : StringSpec({
"사용자 등록, 로그인, 프로필 수정까지" {
// 너무 복잡!
}
})

// ✅ 一つずつ
class SimpleTest : StringSpec({
"사용자 등록" {
// 하나만 테스트
}

"로그인" {
// 별도로 테스트
}

"프로필 수정" {
// 또 별도로
}
})

明確なテスト名

class GoodNaming : StringSpec({
// ❌ 悪い名前
"test1" { }

// ✅ 良い名前
"빈 장바구니의 총액은 0원이다" { }
"할인율 10%를 적용하면 10% 할인된다" { }
"중복 이메일로 가입하면 예외가 발생한다" { }
})

Given-When-Thenパターン

class GWTTest : StringSpec({
"주문 생성 후 결제하면 상태가 PAID가 된다" {
// Given
val order = Order(items = listOf(Item("상품", 10000.0)))

// When
order.pay()

// Then
order.status shouldBe OrderStatus.PAID
}
})

enum class OrderStatus { PENDING, PAID, SHIPPED }

data class Order(
val items: List<Item>,
var status: OrderStatus = OrderStatus.PENDING
) {
fun pay() {
status = OrderStatus.PAID
}
}

🛡️ TDDの利点

1. バグの早期発見

// 最初にテストを書くことで要件を明確に理解する
"음수 금액은 허용하지 않는다" {
shouldThrow<IllegalArgumentException> {
Order(amount = -1000.0)
}
}

// 実装中に検証ロジックが自然に追加される
data class Order(val amount: Double) {
init {
require(amount >= 0) { "금액은 0 이상이어야 합니다" }
}
}

2. リファクタリングのセーフティネット

// テストがあればリファクタリング後も安心
class BeforeRefactor {
fun calculate(price: Double, quantity: Int): Double {
var total = price * quantity
if (quantity > 10) {
total = total * 0.9 // 10개 이상 10% 할인
}
return total
}
}

// リファクタリング
class AfterRefactor {
fun calculate(price: Double, quantity: Int): Double {
val subtotal = price * quantity
val discount = getDiscount(quantity)
return subtotal * (1 - discount)
}

private fun getDiscount(quantity: Int): Double {
return if (quantity > 10) 0.1 else 0.0
}
}

// 테스트가 통과하면 리팩토링 성공!

🤔 よくある質問

Q1. 常にテストを最初に書かなければなりませんか?

A: 複雑なロジックや重要な機能に優先的に適用してください!

// ✅ TDD必須
// - ビジネスロジック
// - 金額計算
// - 検証ロジック

// ❌ TDD任意
// - 単純なgetter/setter
// - UIレイアウト
// - 設定ファイル

Q2. テストをいくつ書けばよいですか?

A: 境界値と例外状況を含めてください!

class ComprehensiveTest : StringSpec({
// 正常ケース
"정상적인 입력" { }

// 境界値
"최소값" { }
"최대값" { }

// 例外
"null 입력" { }
"빈 문자열" { }
"음수" { }
})

Q3. レガシーコードにもTDDを適用できますか?

A: 修正する部分から始めてください!

// 1. 기존 기능에 테스트 추가
// 2. 테스트가 통과하는지 확인
// 3. 리팩토링
// 4. 새 기능은 TDD로

🎬 まとめ

TDDで堅牢なコードを!

重要なポイント:
✅ Red-Green-Refactorサイクル
✅ テストを最初に書く
✅ 小さなステップで進める
✅ リファクタリングのセーフティネット
✅ 設計改善の効果

おめでとうございます! Testingシリーズを完了しました! 🎉

次のステップ: Ktor入門でバックエンド開発を始めてください!