How do I mockk a Bitmap without it breaking Bitmaps in future tests? Let's take the following simplified example...
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
}
}
Let's say may test class is as follows...
@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()
passes if I run it alone. If I include the line that mockks a Bitmap (val mockBitmap: Bitmap = mockk()
), then testSaveBitmapToTempDirectoryWithSuccess()
fails when I run all the tests together. bitmap.compress()
throws NoSuchMethodException: checkRecycled
Similarly, if another test class mockks a Bitmap and is run as a group with this test class, then testSaveBitmapToTempDirectoryWithSuccess()
fails for the same reason.
How do I address this situation? In some tests, I'd like to have a mock Bitmap. In other tests, I'd like to compress a real one.