6

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

Am I in the wrong way to use interceptTestCase()? Thank you very much~

deamon
  • 89,107
  • 111
  • 320
  • 448
Lawrence Ching
  • 423
  • 7
  • 16

2 Answers2

2

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

The root cause is that oneInstancePerTest is true by default(although it's false in kotlin test doc), which means every test scenario will run in the different instances.

In the case in question, The initializing interceptTestCase method ran in instance A, set text to ABC. Then the test case ran in instance B without interceptTestCase.

For more detail, there is an open issue in GitHub:
https://github.com/kotlintest/kotlintest/issues/174

Lawrence Ching
  • 423
  • 7
  • 16
0

You have not initialized the text variable. init called first when you create an object for a class.

You are calling text shouldEqual "ABC" in init block in your code, that time there will be no value in a text variable.

Your function interceptTestCase(context: TestCaseContext, test: () -> Unit) only can be called after the init block.

Initialize the text at the constructor itself like below code, so you won't get this error or make some alternative.

class KotlinTest(private val text: String): StringSpec()
Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66
  • Actually this is not the reason. `text shouldEqual "ABC"` is not called in `init` block, lambda containing `text shouldEqual "ABC"` is only created there, not run. – michalbrz Dec 28 '17 at 17:04