Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过interceptTestCase更改KotlinTest中的测试对象属性_Kotlin_Kotlintest - Fatal编程技术网

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

如何通过interceptTestCase更改KotlinTest中的测试对象属性,kotlin,kotlintest,Kotlin,Kotlintest,我尝试使用interceptTestCase方法为测试用例设置属性,如下所示: class MyTest : ShouldSpec() { private val items = mutableListOf<String>() private var thing = 123 override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { items

我尝试使用interceptTestCase方法为测试用例设置属性,如下所示:

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}")
        }
    }
}
classmytest:ShouldSpec(){
private val items=mutableListOf()
私人物品=123
重写TestCase(上下文:TestCaseContext,test:()->Unit){
项目。添加(“foo”)
东西=456
println(“测试前${items.size}和${thing}”)
测试()
println(“测试后${items.size}和${thing}”)
}
初始化{
应该(“不这样工作”){
println(“在测试期间${items.size}和${thing}”)
}
}
}
我得到的结果是:

在测试1和456之前

在测试0和123期间

在测试1和456之后


因此,我所做的更改在测试用例中是不可见的。在执行每个测试之前,我应该如何更改属性?

您应该通过
TestCaseContext
访问当前规范。每个测试都有其单独的
规范
,例如:

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}")
    }
}
testcase(上下文:TestCaseContext,test:()->Unit){
//v--铸造到这里的特殊规格。
使用(context.spec作为MyTest){
//^---使用with函数获取lambda body中的“receiver”
项目。添加(“foo”)//--

//|是的。因此运行“interceptTestCase”的实例与实际运行测试用例的实例不同?@GarthGilmour是的。对于
Spec
它将创建
N+1
Spec
s。一个用于定义,其他用于测试。