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()的方式是否错误?非常感谢〜
您尚未初始化该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)
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |