【发布时间】:2022-10-17 21:41:22
【问题描述】:
我需要从下面提到的方法中测试三件事:
- 验证
output.write(any<ByteArray>())被调用 - 验证
output.close()被调用 - 断言返回
fullPath
fun saveFile(fullPath: String, model: SomeDataModel): String? {
try {
val output = FileOutputStream(fullPath)
output.write(Base64.decode(model.someString, Base64.DEFAULT))
output.close()
} catch (e: IOException) {
return null
}
return fullPath
}
面临的问题:
- 嘲讽
FileOutputStream
试过:
@Test
fun `saveFile returns file path if fileOutputStream write succeeds`() {
val fullPath = "test/full/path"
val model = SomeDataModel()
val stringByteArray: ByteArray? = someModel.someString?.toByteArray(Charset.defaultCharset())
mockkStatic("android.util.Base64")
every { Base64.decode(model.someString, Base64.DEFAULT) } returns stringByteArray
mockkConstructor(FileOutputStream::class)
val fileOutputStream = mockk<FileOutputStream>()
every { constructedWith<FileOutputStream>(OfTypeMatcher<String>(String::class)) } returns fileOutputStream
// Getting error on above line: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
every { saveFile(fullPath, model) } returns filePath
val result = saveFile(fullPath, model)
verify { fileOutputStream.write(stringByteArray) }
assertEquals(fullPath, result)
}
请帮助我使用 Mockk.io/Mockito 编写正确的测试用例
【问题讨论】:
-
将您的函数包装在具有
FileOutputStream和Base64.decode包装器作为可注入参数的类中(如构造函数)将非常容易 -
嗨@Neo,你能分享示例代码吗?
标签: android unit-testing kotlin mockito mockk