0

I'm trying to do a standard beforeAll/afterAll type setup in the unit tests, but am having some problems. It seems like the interceptSpec functionality is what I want and the documentation explicitly mentions this is good for e.g. cleaning up database resources, but I can't find a good example. Code below:

class MyTest : StringSpec() {
    lateinit var foo: String

    override fun interceptSpec(context: Spec, spec: () -> Unit) {
        foo = "foo"
        println("before spec - $foo")
        spec()
        println("after spec - $foo")
    }

    init {
        "some test" {
            println("inside test - $foo")
        }
    }
}

This results in the below output:

before spec - foo
kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized
    ... stack trace omitted ...
after spec - foo
Danny G
  • 581
  • 4
  • 16

1 Answers1

1

kotlintest 2.x creates new instance of test case for every test. You can either cancel that behaviour clearing flag:

override val oneInstancePerTest = false

Or explicitly add your interceptors to test:

val withFoo: (TestCaseContext, () -> Unit) -> Unit = { context, spec ->
    foo = "foo"
    spec()
}

init {
    "some test" {
        println("inside test - $foo")
    }.config(interceptors = listOf(withFoo))
}
anti_social
  • 323
  • 3
  • 9