我有一些共享通用設置的測試用例。他們都需要兩個可以以相同方式初始化的字段。所以我想我可以將它們提取到lateinit var
字段中,並在測試用例攔截器中創建它們。
但是當我嘗試在我的測試用例中訪問它們時,它們總是拋出一個異常,因爲它們沒有被初始化。
有沒有辦法在每個測試用例之前創建字段?Kotlintest攔截器和遲後變量
這是到目前爲止我的代碼:
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
方法,我看到它在測試之前執行和屬性初始化設置一個斷點。然後我向前邁進測試,並在其中的屬性不再初始化。