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

Law*_*ing 5 kotlin kotlintest

I'm trying to find a way to set up variable before each test. Just like the @Before method in Junit. Go through the doc from kotlin-test, I found that I can use interceptTestCase() interface. But unfortunately, the code below will trigger 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()
}
}
Run Code Online (Sandbox Code Playgroud)

我使用interceptTestCase()的方式是否错误?非常感谢〜

Bhu*_* BS 0

您尚未初始化该text变量。当您为类创建对象时,首先调用 init 。

您在代码中调用text shouldEqual "ABC"init,此时text变量中将没有值。

您的函数interceptTestCase(context: TestCaseContext, test: () -> Unit)只能在块之后调用init

像下面的代码一样在构造函数本身初始化文本,这样您就不会收到此错误或做出其他选择。

class KotlinTest(private val text: String): StringSpec()
Run Code Online (Sandbox Code Playgroud)