Kotlin Advent Calendar 2021の12日目の記事です
概要
Kotestのテスト実行単位とhooksについて
背景
KotestのLifecycle hooksには (before
|after
)(Each
|Container
|Test
) があるがBehaviorSpecでの実用上の違いが分かりにくい
結論
Each
:Then
Container
:Given
/When
Test
:Given
/When
/Then
詳細
ドキュメントの説明
公式ドキュメント ではhook対象は以下のように説明されている
Each
:TestType.Test
Container
:TestType.Container
Test
:TestCase
しかしこれだけでは何のことか分かりにくい
TestCaseとTestTypeの定義
data class TestCase(
val type: TestType,
// ...
)
enum class TestType {
Container, Test
}
TestCase
はテストの実行単位で TestType
は TestCase
の分類であることが分かる
イメージは TestCase
⊃ TestType.Container
,TestType.Test
試したコード
beforeEach
class SandboxSpec : BehaviorSpec() {
init {
beforeEach { // it: TestCase
println("hooked TestType: %s".format(it.type))
}
Given("a") {
println("run Given")
When("b") {
println("run When")
Then("c") {
println("run Then")
}
}
}
}
}
run Given
run When
hooked TestType: Test
run Then
Then
のみがhookされている
beforeContainer
class SandboxSpec : BehaviorSpec() {
init {
beforeContainer { // it: TestCase
println("hooked TestType: %s".format(it.type))
}
Given("a") {
println("run Given")
When("b") {
println("run When")
Then("c") {
println("run Then")
}
}
}
}
}
hooked TestType: Container
run Given
hooked TestType: Container
run When
run Then
Given
/ When
がhookされている
beforeTest
class SandboxSpec : BehaviorSpec() {
init {
beforeTest { // it: TestCase
println("hooked TestType: %s".format(it.type))
}
Given("a") {
println("run Given")
When("b") {
println("run When")
Then("c") {
println("run Then")
}
}
}
}
}
hooked TestType: Container
run Given
hooked TestType: Container
run When
hooked TestType: Test
run Then
Given
/ When
/ Then
がhookされている