gpt4 book ai didi

kotlin - 如何通过interceptTestCase更改KotlinTest中的测试对象属性

转载 作者:行者123 更新时间:2023-12-01 01:50:05 24 4
gpt4 key购买 nike

我正在尝试使用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}")
}
}

关于kotlin - 如何通过interceptTestCase更改KotlinTest中的测试对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45081057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com