我正在尝试找到一种在每次测试之前设置变量的方法。就像Junit中的@Before方法一样。通过kotlin-test的文档,我发现我可以使用interceptTestCase()接口(interface)。但不幸的是,下面的代码将触发异常: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()
}
}
我使用interceptTestCase()的方式是否错误?
非常感谢你〜
最佳答案
一种快速的解决方案是在测试用例中添加以下语句:override val oneInstancePerTest = false
根本原因是oneInstancePerTest默认情况下为true(尽管在kotlin测试文档中为false),这意味着每种测试方案都将在不同的实例中运行。
在这种情况下,
初始化interceptTestCase
方法在实例A中运行,将文本设置为ABC。然后,测试用例在实例B中运行,没有interceptTestCase
。
有关更多详细信息,GitHub中有一个 Unresolved 问题:
https://github.com/kotlintest/kotlintest/issues/174
关于kotlin - 如何在每次使用Kotlin-test框架进行测试之前初始化变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45618878/