我正在尝试在设备测试中进行标准的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
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))
}