【问题标题】:Unit testing | Mocking FileOutputStream using Mockk.io单元测试 |使用 Mockk.io 模拟 FileOutputStream
【发布时间】: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 编写正确的测试用例

【问题讨论】:

  • 将您的函数包装在具有FileOutputStreamBase64.decode 包装器作为可注入参数的类中(如构造函数)将非常容易
  • 嗨@Neo,你能分享示例代码吗?

标签: android unit-testing kotlin mockito mockk


【解决方案1】:

every { constructedWith&lt;FileOutputStream&gt;(OfTypeMatcher&lt;String&gt;(String::class)) } returns fileOutputStream 行中,您不能返回模拟对象fileOutputStream,而是一个非模拟对象。看看https://mockk.io/#constructor-mocks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2011-04-11
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多