robin
robin

Reputation: 1925

Issue with lateinit in test case

I have a kotlin Ut like below

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class FileOpenerTest {

    private val file = mockk<Resource>()
    private lateinit var target: FileOpener

    @BeforeAll
    fun setup() {
        val file = File("./src/test/resources/sample.csv")
        every { file.file } returns file
        target = FileOpener(file)
    }

    @Test
    fun `get  documents for indexing from  file`() {
        val docs = target.startIndexing()
        verify { docs.size == 3 }
    }
}

the test case is always failing saying

kotlin.UninitializedPropertyAccessException: lateinit property target has not been initialized

But I am initialising it in the setup method, please help me to fix the issue ?

Upvotes: 1

Views: 1650

Answers (1)

Neo
Neo

Reputation: 2039

Your setup annotation @BeforeAll is applied only on static functions:

@BeforeAll annotated method MUST be a static method otherwise it will throw runtime error.

Source

So your method is not executed in JUnit. Either put the method and the field in your companion object or initialize it differently, like with @Before

Upvotes: 1

Related Questions