Kotlintest拦截器和lateinit变量

我有一些共享通用设置的测试用例。 他们都需要两个可以以相同的方式初始化的领域。 所以我想我可以将它们提取到lateinit var字段中,并在测试用例拦截器中创建它们。
但是当我尝试在我的测试用例中访问它们时,它们总是抛出异常,因为它们没有被初始化。
有没有办法在每个测试用例之前创建字段?

这是我的代码到目前为止:

 class ElasticsearchFieldImplTest : WordSpec() { // These 2 are needed for every test lateinit var mockDocument: ElasticsearchDocument lateinit var mockProperty: KProperty<*> override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { // Before Each mockDocument = mock() mockProperty = mock { on {name} doReturn Gen.string().generate() } // Execute Test test() // After Each } init { "ElasticsearchFields" should { "behave like normal var properties" { val target = ElasticsearchFieldImpl<Any>() // Here the exception is thrown target.getValue(mockDocument, mockProperty) shouldBe null val testValue = Gen.string().generate() target.setValue(mockDocument, mockProperty, testValue) target.getValue(mockDocument, mockProperty) shouldBe testValue } } } } 

当我用调试器遍历它,并在interceptTestCase方法中设置断点时,我发现它在测试之前执行并且属性被初始化。 然后我继续进行测试,并在其中的属性不会被初始化。

在初始化之前,你不应该访问lateinit vars

问题是你正在init {}块内访问你的lateinit var ,它是默认的构造函数,并且在interceptTestCase()之前被调用。

最简单的方法就是使mockDocumentmockProperty空。

 var mockDocument: ElasticsearchDocument? = null var mockProperty: KProperty<*>? = null 

如果你想测试崩溃,如果这些领域没有初始化添加!! 修改:

 init { "ElasticsearchFields" should { "behave like normal var properties" { val target = ElasticsearchFieldImpl<Any>() // Here the exception is thrown target.getValue(mockDocument!!, mockProperty!!) shouldBe null val testValue = Gen.string().generate() target.setValue(mockDocument!!, mockProperty!!, testValue) target.getValue(mockDocument!!, mockProperty!!) shouldBe testValue } } }