Akash Patel
Akash Patel

Reputation: 199

getting error Missing calls inside every { ... } block in writing unit test cases in kotlin + Mockk + Junit5

the function I am testing,

class FileUtility {
    companion object {
        @JvmStatic
        fun deleteFile(filePath: String) {
            try {
                val file = getFileObject(filePath)
                file.delete()
            } catch (ex :Exception) {
                log.error("Exception while deleting the file", ex)
            }
        }
    }
}

Unit test,

@Test
fun deleteFileTest() {
    val filePath = "filePath"
    val file = mockk<File>()
    every { getFileObject(filePath) } returns file
    deleteFile(filePath)
    verify { file.delete() }
}

getting the following error on running this test case

 io.mockk.MockKException: Missing calls inside every { ... } block.

is this any bug or am I writing wrong test case?

Upvotes: 5

Views: 9101

Answers (1)

sidgate
sidgate

Reputation: 15244

Assuming getFileObject is a top level function in FileUtility.kt file, you need to mock module wide functions with mockkStatic(...) with argument as the module’s class name.

For example “pkg.FileKt” for module File.kt in the pkg package.

@Test
fun deleteFileTest() {
    val file = mockk<File>()
    mockkStatic("pkg.FileKt")
    
    val filePath = "filePath"
    every { getFileObject(filePath) } returns file
    every {file.delete()} answers {true}

    deleteFile(filePath)
    
    verify { file.delete() }
}

Upvotes: 4

Related Questions