问题描述
我还是 Kotlin 和 Kotest 的新手,我正在努力寻找一种方法来创建 BDD 风格的测试。我的问题是该框架如何能够创建可重用的 Given 步骤。 例如:
class KotestTest1 : BehaviorSpec({
given("State A") {
// Verify the State A exists
println("Verify the State A exists")
`when`("Action A") {
// Execute Action A
println("Execute Action A")
then("State => A1") {
// Verify the state is Now A1
println("Verify the state is Now A1")
}
}
}
})
class KotestTest2 : BehaviorSpec({
given("State A") {
// Verify the State A exists
println("Verify the State A exists")
`when`("Action B") {
// Execute Action B
println("Execute Action B")
then("State => B1") {
// Verify the state is Now B1
println("Verify the state is Now B1")
}
}
}
})
所以这里我有给定步骤“状态 A”的代码重复。我想知道如何创建整个步骤的预期方式。看起来 given(description: String) 是我必须重复的内容,对于 println("Verify the State A exists")
我只是将其提取为通用函数。
我希望我可以更好地构建我的代码,以便我可以创建 Given 步骤并在多个测试场景中使用它们。对此有什么建议吗?
解决方法
我认为最常用的方法是将两个测试合并为一个,并在其中嵌套测试:
class KotestTest : BehaviorSpec({
Given("State A") {
When("Action A") {
Then("State => A1") {
}
}
When("Action B") {
Then("State => B1") {
}
}
}
})