如何在每次测试之前使用kotlin-test框架初始化variables

我试图find一种方法来设置每个测试前的variables。 就像Junit中的@Before方法一样。 通过kotlin-test的文档,我发现我可以使用interceptTestCase()接口。 但不幸的是,下面的代码会触发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() } } 

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

一个快速的解决方案是在测试用例中添加下面的语句:
override val oneInstancePerTest = false

根本原因是默认情况下oneInstancePerTest为true(尽管在kotlin测试文档中它是错误的),这意味着每个测试场景都将在不同的实例中运行。

在这种情况下,初始化interceptTestCase方法在实例A中运行 ,将文本设置为ABC 。 然后测试用例在没有interceptTestCase实例B中运行。

有关更多详细信息,GitHub中存在一个未解决的问题:
https://github.com/kotlintest/kotlintest/issues/174

您尚未初始化textvariables。 在为类创建对象时首先调用init。

你在代码中的init块中调用text shouldEqual "ABC" ,那时textvariables中没有值。

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

在构造函数本身初始化文本就像下面的代码,所以你不会得到这个错误或做出一些替代。

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