给定是来自 kotlin-test github 文档的示例,但我在这里没有看到 beforeEach 或 beforeClass 概念。我想明白,
- 如何在每次测试前执行一次代码/方法
- 如何在每个测试类之前执行一次代码/方法
class MyTests : StringSpec({
"length should return size of string" {
"hello".length shouldBe 5
}
"startsWith should test for a prefix" {
"world" should startWith("wor")
}
})
与你自己的答案@JTeam非常相似,但使用 init {} 构造函数块来声明你的测试,然后你可以直接在类中重写方法。
class MyTest : StringSpec() {
override fun beforeTest(description: Description) {
super.beforeTest(description)
println("Before every spec/test case")
}
override fun beforeSpec(description: Description, spec: Spec) {
super.beforeSpec(description, this)
println("Before every test suite")
}
override fun afterTest(description: Description, result: TestResult) {
super.afterTest(description, result)
println("After every spec/test case")
}
override fun afterSpec(description: Description, spec: Spec) {
super.afterSpec(description, spec)
println("After every test suite")
}
init {
"test should run " {
"Hello".shouldHaveLength(4)
}
"test2 should run " {
"Hello World".shouldHaveLength(10)
}
}
}
在较新版本的Kotest
中(我认为从 4.0.0 开始(,TestCofiguration
上有 lifecylce 函数,不再需要 init 块:
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.string.shouldHaveLength
class MyTest : StringSpec({
beforeTest {
println("Before every spec/test case")
}
beforeSpec {
println("Before every test suite")
}
afterTest {
println("After every spec/test case")
}
afterSpec {
println("After every test suite")
}
"test 1 " {
println("run test 1")
"Hello" shouldHaveLength 4
}
"test 2 " {
println("run test 2")
"Hello World" shouldHaveLength 10
}
})
更多信息
在对github 文档和 kotlin-test 框架源代码进行了一些研究之后,下面是在 Test、beforeSpec、afterTest、afterSpec 之前编写的代码
class MyTest : StringSpec({
"test should run " {
"Hello".shouldHaveLength(4)
}
"test2 should run " {
"Hello World".shouldHaveLength(10)
}
}) {
override fun beforeTest(description: Description) {
super.beforeTest(description)
println("Before every spec/test case")
}
override fun beforeSpec(description: Description, spec: Spec) {
super.beforeSpec(description, this)
println("Before every test suite")
}
override fun afterTest(description: Description, result: TestResult) {
super.afterTest(description, result)
println("After every spec/test case")
}
override fun afterSpec(description: Description, spec: Spec) {
super.afterSpec(description, spec)
println("After every test suite")
}
}
这看起来不优雅,如果有什么方法可以让它优雅,请发布它。