환경 설정
FIRST 규칙
📌 테스트 코드가 지켜야 할 규칙
- Fast: 테스트는 빠르게 동작해야 한다.
- Independent : 각 테스트는 서로 의존해선 안되며, 독립적으로 그리고 아무 순서로 실행해도 괜찮아야 한다.
- Repeatable : 테스트는 어떤 환경에서도 반복 가능해야 한다.
- Self-Validating : 테스트는 성공 또는 실패로 bool 값으로 결과를 내어 검증해야 한다.
- Timely : 테스트는 적시에 즉, 테스트하려는 실제 코드를 구현하기 직전에 구현해야 한다.
data class Item(
val name: String,
val weight: Int,
)
class Bag(
val maxWeight: Int,
) {
init {
if (maxWeight <= 0) {
throw Exception("가방의 최대 무게가 잘못 설정되었습니다.")
}
}
val itemList: MutableList<Item> = mutableListOf()
val currentWeight = this.itemList.fold(0) { acc, item -> acc + item.weight }
fun putItem(item: Item) {
if (item.weight + currentWeight > maxWeight) {
throw Exception("가방에 아이템을 넣을 수 없습니다.")
}
this.itemList.add(item)
}
fun removeItem(item: Item) {
this.itemList.remove(item)
}
}
테스트 코드
class BagTest : BehaviorSpec({
Given("a valid max weight") {
val validMaxWeight = 10
When("execute constructor") {
val result = Bag(validMaxWeight)
Then("max weight should be valid max weight") {
result.maxWeight shouldBe validMaxWeight
}
}
}
Given("a max weight = 0") {
val maxWeight = 0
When("execute constructor") {
val exception = shouldThrow<Exception> { Bag(maxWeight) }
Then("exception message should be expected") {
exception.message shouldBe "가방의 최대 무게가 잘못 설정되었습니다."
}
}
}
Given("a max weight is negative") {
val maxWeight = -10
When("execute constructor") {
val exception = shouldThrow<Exception> { Bag(maxWeight) }
Then("exception message should be expected") {
exception.message shouldBe "가방의 최대 무게가 잘못 설정되었습니다."
}
}
}
})
'Back-End (Web) > Kotlin' 카테고리의 다른 글
[Kotlin] Kotlin의 객체지향 (0) | 2025.02.12 |
---|---|
[Kotlin] Kotlin의 사용 (0) | 2025.02.11 |
[Kotlin] Kotlin이란? (0) | 2025.02.10 |