如何通过 interceptTestCase 更改 KotlinTest 中的测试对象属性
How to alter test object properties in KotlinTest via interceptTestCase
我正在尝试使用 interceptTestCase 方法为 KotlinTest 中的测试用例设置属性,如下所示:
class MyTest : ShouldSpec() {
private val items = mutableListOf<String>()
private var thing = 123
override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
items.add("foo")
thing = 456
println("Before test ${items.size} and ${thing}")
test()
println("After test ${items.size} and ${thing}")
}
init {
should("not work like this") {
println("During test ${items.size} and ${thing}")
}
}
}
我得到的输出是:
Before test 1 and 456
During test 0 and 123
After test 1 and 456
所以我所做的更改在测试用例中是不可见的。我应该如何在执行每个测试之前更改 属性?
您应该通过 TestCaseContext
访问当前规范。每个测试都有其单独的 Spec
,例如:
override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
// v--- casting down to the special Spec here.
with(context.spec as MyTest) {
//^--- using with function to take the `receiver` in lambda body
items.add("foo") // --
// |<--- update the context.spec properties
thing = 456 // --
println("Before test ${items.size} and ${thing}")
test()
println("After test ${items.size} and ${thing}")
}
}
我正在尝试使用 interceptTestCase 方法为 KotlinTest 中的测试用例设置属性,如下所示:
class MyTest : ShouldSpec() {
private val items = mutableListOf<String>()
private var thing = 123
override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
items.add("foo")
thing = 456
println("Before test ${items.size} and ${thing}")
test()
println("After test ${items.size} and ${thing}")
}
init {
should("not work like this") {
println("During test ${items.size} and ${thing}")
}
}
}
我得到的输出是:
Before test 1 and 456
During test 0 and 123
After test 1 and 456
所以我所做的更改在测试用例中是不可见的。我应该如何在执行每个测试之前更改 属性?
您应该通过 TestCaseContext
访问当前规范。每个测试都有其单独的 Spec
,例如:
override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
// v--- casting down to the special Spec here.
with(context.spec as MyTest) {
//^--- using with function to take the `receiver` in lambda body
items.add("foo") // --
// |<--- update the context.spec properties
thing = 456 // --
println("Before test ${items.size} and ${thing}")
test()
println("After test ${items.size} and ${thing}")
}
}