我正在用嘲笑和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
}
}
}
单元测试用例如下,
@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}
}
出现以下错误,
Expected java.lang.Exception to be thrown, but nothing was thrown.
另外,verify { file.isHidden}
行不起作用,它给出以下错误。
java.lang.AssertionError: Verification failed: call 1 of 1: File(#1).isHidden()) was not called
答案 0 :(得分:2)
您正在测试的函数实例化其自己的File
实例。它没有使用您创建的模拟实例。
对于这种类型的测试,您需要模拟构造函数,以便模拟该类的任何实例化实例。您可以在https://mockk.io/#constructor-mocks处阅读更多内容,但这是您的示例(具有不同的断言库):
@Test
fun `get file object test throws exception when file path is hidden`() {
val filePath = "filepath"
mockkConstructor(File::class)
every { anyConstructed<File>().isHidden } returns true
assertThat{
getFileObject(filePath)
}.isFailure().isInstanceOf(IllegalArgumentException::class)
verify { anyConstructed<File>().isHidden}
}