0

如何在以后的测试中模拟位图而不破坏位图?让我们看下面的简化示例...

class FileHelper @Inject constructor(private val application: Application) {
    fun saveBitmapToTempDirectory(bitmap: Bitmap, filename: String, format: Bitmap.CompressFormat): File {
        val tempDirectory = File(application.cacheDir, "images").apply { mkdirs() }
        val file = File(tempDirectory, "$filename.${format.name.toLowerCase()}")
        FileOutputStream(file).use { outStream ->
            bitmap.compress(format, 100, outStream)
        }
        return file
    }
}

假设可能测试类如下......

@RunWith(AndroidJUnit4::class)
class FileHelperTest {

    @Test
    fun otherTest(){
//        When I uncomment the next line, I get NoSuchMethodException: checkRecycled in testSaveBitmapToTempDirectoryWithSuccess()
//        val mockBitmap: Bitmap = mockk()
//        Do stuff using a mockBitmap

//        The following block also causes the same issue (even with a real decoded Bitmap).
//        mockkStatic(BitmapFactory::class)
//        every {
//            BitmapFactory.decodeStream(mockInputStream)
//        } returns realDecodedBitmap
//        unmockkStatic(BitmapFactory::class)

//        None of the following work:
//        unmockkAll()
//        clearAllMocks()
//        unmockkStatic(Bitmap::class)
//        clearMocks(mockBitmap)
//        clearStaticMockk(Bitmap::class)
    }

    @Test
    fun testSaveBitmapToTempDirectoryWithSuccess() {
        val application = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as Application
        val file = FileHelper(application).saveBitmapToTempDirectory(
            BitmapFactory.decodeResource(application.resources, R.drawable.mypic),
            "bitmap",
            Bitmap.CompressFormat.PNG
        )
        assertTrue(file.absolutePath.endsWith("bitmap.png"))
    }
}

testSaveBitmapToTempDirectoryWithSuccess()如果我单独运行它会通过。如果我包含模拟 Bitmap ( val mockBitmap: Bitmap = mockk()) 的行,那么testSaveBitmapToTempDirectoryWithSuccess()当我一起运行所有测试时会失败。bitmap.compress()投掷NoSuchMethodException: checkRecycled

类似地,如果另一个测试类模拟了一个位图并与这个测试类作为一个组运行,那么testSaveBitmapToTempDirectoryWithSuccess()由于同样的原因而失败。

我该如何解决这种情况?在一些测试中,我想要一个模拟位图。在其他测试中,我想压缩一个真实的。

4

0 回答 0