跳至正文

🔄 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介紹中開始後端開發!