如何在kotlintest 2.x(interceptSpec)中正确初始化共享资源
在单元测试中,我试图在之前/如何在kotlintest 2.x(interceptSpec)中正确初始化共享资源,kotlin,kotlintest,Kotlin,Kotlintest,在单元测试中,我试图在之前/之后类型设置之前做一个标准的,但是我遇到了一些问题。这似乎是我想要的功能,文档中明确提到这有利于清理数据库资源,但我找不到一个好的例子。代码如下: class MyTest : StringSpec() { lateinit var foo: String override fun interceptSpec(context: Spec, spec: () -> Unit) { foo = "foo" print
之后
类型设置之前做一个标准的,但是我遇到了一些问题。这似乎是我想要的功能,文档中明确提到这有利于清理数据库资源,但我找不到一个好的例子。代码如下:
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
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))
}