BitmapWriter implements DiskCache.Writer { @Override public boolean write(File file) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (bitmap.hasAlpha()) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } else { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); } return true; } catch (IOException e) { Log.w(TAG, "Could not write bitmap to file", e); } finally { IOUtils.close(fos); } return false; } BitmapWriter(Bitmap bitmap); @Override boolean write(File file);  }
@Test public void testWritesPng() { File file = new File(getContext().getCacheDir(), "test_file"); Bitmap bitmap = Mockito.mock(Bitmap.class); Mockito.when(bitmap.hasAlpha()).thenReturn(true); Mockito.when( bitmap.compress((Bitmap.CompressFormat) Mockito.any(), Mockito.anyInt(), (OutputStream) Mockito.any())). thenReturn(true); Mockito.when(bitmap.getWidth()).thenReturn(400); Mockito.when(bitmap.getHeight()).thenReturn(400); BitmapWriter writer = new BitmapWriter(bitmap); boolean result = writer.write(file); Assert.assertTrue(result); ShadowBitmapFactory.provideWidthAndHeightHints(file.getAbsolutePath(), 400, 400); Bitmap writtenBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); Assert.assertNotNull(writtenBitmap); Assert.assertEquals(bitmap.getWidth(), writtenBitmap.getWidth()); Assert.assertEquals(bitmap.getHeight(), writtenBitmap.getHeight()); }
@Test public void testWritesJpeg() { File file = new File(getContext().getCacheDir(), "test_file"); Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565); BitmapWriter writer = new BitmapWriter(bitmap); boolean result = writer.write(file); Assert.assertTrue(result); ShadowBitmapFactory.provideWidthAndHeightHints(file.getAbsolutePath(), 200, 200); Bitmap writtenBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); Assert.assertNotNull(writtenBitmap); Assert.assertEquals(bitmap.getWidth(), writtenBitmap.getWidth()); Assert.assertEquals(bitmap.getHeight(), writtenBitmap.getHeight()); }
@Test public void testWriteFailsGracefully() { File file = new File("http: Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565); BitmapWriter writer = new BitmapWriter(bitmap); boolean result = writer.write(file); Assert.assertFalse(result); }