android - 如何在未来的测试中使用 mockk 模拟 Bitmap 而不会影响 bitmap.compress
问题描述
如何在以后的测试中模拟位图而不破坏位图?让我们看下面的简化示例...
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()
由于同样的原因而失败。
我该如何解决这种情况?在一些测试中,我想要一个模拟位图。在其他测试中,我想压缩一个真实的。
解决方案
推荐阅读
- android - 是否可以重用部分 AndroidManifest.xml 文件?
- c - C 中最快的 fgets 实现
- asp.net-mvc - 使用带有 JSON 输入的 Bind 属性
- php - 在 PHP 中包含一个 IF 和他对应的 else
- node.js - Nodejs Telegram bot 消息收到轮询错误
- android - 如何为封面图片Android Studio添加另一个案例
- django - django.db.utils.OperationalError:没有这样的表:Schedule_swimmingscore
- logstash - Logstash HTTPD_COMBIEDLOG 未定义错误
- android - 使用 BroadcastReceiver 制作闹钟
- c++ - C ++在向量中查找重复符号