我正在尝试在单元测试中执行标准beforeAll
/ afterAll
类型设置,但遇到了一些问题。似乎interceptSpec
功能是我想要的,文档明确提到这对于例如清理数据库资源,但我找不到一个好例子。代码如下:
class MyTest : StringSpec() {
lateinit var foo: String
override fun interceptSpec(context: Spec, spec: () -> Unit) {
foo = "foo"
println("before spec - $foo")
spec()
println("after spec - $foo")
}
init {
"some test" {
println("inside test - $foo")
}
}
}
这导致以下输出:
before spec - foo
kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized
... stack trace omitted ...
after spec - foo
答案 0 :(得分:1)
kotlintest
2.x为每个测试创建测试用例的新实例。您可以取消该行为清除标记:
override val oneInstancePerTest = false
或明确添加您的拦截器进行测试:
val withFoo: (TestCaseContext, () -> Unit) -> Unit = { context, spec ->
foo = "foo"
spec()
}
init {
"some test" {
println("inside test - $foo")
}.config(interceptors = listOf(withFoo))
}