How to change test object properties in KotlinTest via interceptTestCase

I am trying to use the interceptTestCase method to set properties for a test case in KotlinTest , as shown below:

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}")
        }
    }
}

The output I get is:

Before test 1 and 456

During test 0 and 123

After tests 1 and 456

So, the changes I made are not displayed in the test case. How do I change a property before each test run?

+4
source share
1 answer

You need to access the current specification through TestCaseContext. Each test has its own highlight Spec, for example:

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}")
    }
}
+3
source

Source: https://habr.com/ru/post/1681362/


All Articles