🔄 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介绍中开始后端开发!