4

I am trying to use the interceptTestCase method to set up properties for a test case in KotlinTest as 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 that I get is:

Before test 1 and 456

During test 0 and 123

After test 1 and 456

So the changes I have made are not visible within the test case. How should I change a property prior to each test being executed?

Community
  • 1
  • 1
Garth Gilmour
  • 11,124
  • 5
  • 25
  • 35

1 Answers1

3

you should access the current spec via TestCaseContext. each test has its separated 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}")
    }
}
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • Yes that works. So the instance in which 'interceptTestCase' is run is a different instance from that in which the test case actually runs? – Garth Gilmour Jul 13 '17 at 13:22
  • @GarthGilmour yes. for a `Spec` it will create `N+1` `Spec`s. one for the definition, others for the tests. – holi-java Jul 13 '17 at 13:24