我有一些共享通用设置的测试用例。他们都需要两个可以以相同方式初始化的字段。所以我想我可以将它们提取到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
方法,我看到它在测试之前执行和属性初始化设置一个断点。然后我向前迈进测试,并在其中的属性不再初始化。