小编Aka*_*tel的帖子

在 kotlin + Mockk + Junit5 中编写单元测试用例时出现错误 Missing Calls inside every { ... } block

我正在测试的功能,

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)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试,

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

运行此测试用例时出现以下错误

 io.mockk.MockKException: Missing calls inside every { ... } block.
Run Code Online (Sandbox Code Playgroud)

这是任何错误还是我写了错误的测试用例?

kotlin junit5 mockk

5
推荐指数
1
解决办法
8806
查看次数

如何使用mock.io模拟内部构造的实例?

我正在mockk和Junit5中为FileUtility类的伴随对象中定义的静态方法编写单元测试用例。

方法如下,

class FileUtility {

    companion object {
        fun getFileObject(fileName: String): File {
            require(!StringUtils.isBlank(fileName)) { "Expecting a valid filePath" }
            val file = File(fileName)
            if (file.isHidden)
                throw llegalArgumentException()
            return file
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

单元测试用例如下,

@Test
fun `get file object test throws exception when file path is hidden`() {
    val filePath = "filepath"
    val file = mockk<File>()
    every { file.isHidden } returns true
    assertThrows(IllegalArgumentException::class.java) {
        getFileObject(filePath)
    }
    verify { file.isHidden}
}
Run Code Online (Sandbox Code Playgroud)

出现以下错误,

Expected java.lang.Exception to be thrown, but nothing was thrown. …
Run Code Online (Sandbox Code Playgroud)

unit-testing kotlin junit5 mockk mockito-kotlin

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

junit5 ×2

kotlin ×2

mockk ×2

mockito-kotlin ×1

unit-testing ×1