samedi 26 août 2017

Kotlintest interceptor and lateinit vars

I have some testcases that share a common setup. They all need two fields which can be initialized in the same way. So I thought I can extract them into lateinit var fields and create them in an test-case-interceptor.
But when I try to access them in my testcases they always throw an exception because they are not initialized.
Is there a way to create the fields before every testcase?

Here is my code so far:

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
            }
        }
    }
}

When I step through it with a debugger and set a breakpoint in the interceptTestCase methods I see that it is executed before the test and that the properties are initialized. Then I step forward to the test and in it the properties are not initialized anymore.

Aucun commentaire:

Enregistrer un commentaire