我有一些共同设置的测试案例。它们都需要两个可以以相同方式初始化的字段。因此,我想我可以将它们提取到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方法中设置一个断点时,我会看到它在测试之前执行,并且属性已经初始化。然后,我前进到测试,在它中,属性不再初始化。
发布于 2017-12-28 17:17:29
init的答案是不正确的。这不是kotlintest的工作原理-- in lambda只创建而不是运行。因此您没有在init块中访问您的lateinit var。它们只是没有任何赋值。
这不起作用,因为kotlintest中的bug,这里描述了(实际上几乎解决了):https://github.com/kotlintest/kotlintest/issues/174
简而言之,在类的不同实例上调用interceptTestCase,而不是实际测试。所以它对你的测试没有任何影响。
解决方法是重写属性:override val oneInstancePerTest = false
然后只有一个实例,interceptTestCase工作正常,但您必须记住----所有测试的只有一个实例。
Kotlintest 3.0将不受此bug影响。(但在默认情况下,所有测试都可能有一个实例。)
发布于 2017-08-27 06:06:28
在初始化lateinit vars之前,不应该访问它们。
问题在于,您正在访问lateinit var块中的init {}块,该块是默认构造函数,在interceptTestCase()之前调用。
这里最简单的方法就是使mockDocument和mockProperty为空。
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
}
}
}https://stackoverflow.com/questions/45896425
复制相似问题