0

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

1 回答 1

1

kotlintest2.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))
}
于 2017-12-08T15:01:38.793 回答