How can I initialize a variable before each test using the kotlin-test framework

I am trying to find a way to set a variable before each test. Just like the @Before method in Junit. Go through the doc from kotlin-test, I found that I can use the interceptTestCase () interface. But unfortunately, the code below throws an exception:

kotlin.UninitializedPropertyAccessException: lateinit property text has not been initialized

class KotlinTest: StringSpec() {
lateinit var text:String
init {
    "I hope variable is be initialized before each test" {
        text shouldEqual "ABC"
    }

    "I hope variable is be initialized before each test 2" {
        text shouldEqual "ABC"
    }
}

override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
    println("interceptTestCase()")
    this.text = "ABC"
    test()
}
}

Am I using interceptTestCase () incorrectly? Thanks a lot ~

+4
source share
2 answers

A quick solution is to add the instruction below in the test case:
override val oneInstancePerTest = false

, oneInstancePerTest ( kotlin test doc), , .

, interceptTestCase A, ABC. B interceptTestCase.

GitHub :
https://github.com/kotlintest/kotlintest/issues/174

+2

text. init , .

text shouldEqual "ABC" init , text .

interceptTestCase(context: TestCaseContext, test: () -> Unit) init.

, , .

class KotlinTest(private val text: String): StringSpec()
0

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


All Articles