Kotlin
JUnit5 + Kotest 기초
Kotlin 친화적인 테스트 프레임워크로 읽기 쉬운 테스트를 작성합니다.
// build.gradle.kts 의존성:
// testImplementation("io.kotest:kotest-runner-junit5:5.8.0")
// testImplementation("io.kotest:kotest-assertions-core:5.8.0")
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldThrow
class CalculatorTest : DescribeSpec({
val calc = Calculator()
describe("덧셈") {
it("양수 + 양수") {
calc.add(2, 3) shouldBe 5
}
it("음수 포함") {
calc.add(-1, 1) shouldBe 0
}
}
describe("나눗셈") {
it("정상 나눗셈") {
calc.divide(10, 2) shouldBe 5.0
}
it("0으로 나누면 예외") {
shouldThrow<ArithmeticException> {
calc.divide(10, 0)
}
}
}
})
// JUnit5 스타일
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
class CalcJUnit {
@Test
fun `두 수의 합`() { // 백틱으로 한글 테스트명 가능
assertEquals(5, Calculator().add(2, 3))
}
}
class Calculator {
fun add(a: Int, b: Int) = a + b
fun divide(a: Int, b: Int): Double {
if (b == 0) throw ArithmeticException("0으로 나눌 수 없음")
return a.toDouble() / b
}
}