LoginSignup
1
0

More than 3 years have passed since last update.

jest, rspec経験者向けkotlintest事始め

Last updated at Posted at 2019-09-11

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を見てください。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0