build.gradleにkotlintestを追加
build.gradle
test {
useJUnitPlatform()
}
dependencies {
testImplementation 'io.kotlintest:kotlintest-runner-junit5:3.3.2'
}
DescribeSpecを用いてテストを記述
下記のようにrspec, jestのような雰囲気でdescribe, (jestにはないけど)context, itを使ってテストを書いていくことができます。
DurationUtilsTest.kt
import io.kotlintest.matchers.types.shouldBeTypeOf
import io.kotlintest.shouldThrow
import io.kotlintest.specs.DescribeSpec
import java.lang.IllegalArgumentException
import org.joda.time.Duration
class DurationUtilsTest : DescribeSpec({
describe("#parseDuration") {
fun shouldThrowIllegalArgumentException(duration: String) {
shouldThrow<IllegalArgumentException> { DurationUtils.parseDuration(duration) }
}
context("when invalid time suffix") {
it("throws illegal argument exception") {
shouldThrowIllegalArgumentException("1")
}
}
context("when value is negative") {
context("when second") {
it("throws illegal argument exception") {
shouldThrowIllegalArgumentException("-1s")
}
}
}
context("when value is positive") {
fun shouldBeTypeOfDuration(duration: String) {
DurationUtils.parseDuration(duration).shouldBeTypeOf<Duration>()
}
context("when second") {
it("returns duration") {
shouldBeTypeOfDuration("1s")
}
}
}
}
})
kotlintestではDescribeSpec以外の書き方もできます。
詳しくはkotlintest stylesを見てください。