如何在 kotlintest 2.x (interceptSpec) 中正确初始化共享资源

how to properly initialize shared resource in kotlintest 2.x (interceptSpec)

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