Aka*_*tel 3 unit-testing kotlin junit5 mockk mockito-kotlin
我正在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)
此外,该verify { file.isHidden}线路无法正常工作,会出现以下错误。
java.lang.AssertionError: Verification failed: call 1 of 1: File(#1).isHidden()) was not called
Run Code Online (Sandbox Code Playgroud)
您正在测试的函数实例化它自己的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}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13022 次 |
| 最近记录: |