Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android robolectric unit test load bitmap from drawable

I am trying to load a bitmap from a drawable in my resources, but it appears to be empty when the following code is run in unit tests, but not empty when run from a normal activity:

val bitmapImage = BitmapFactory.decodeResource(context!!.resources, R.drawable.my_image)
val bos = ByteArrayOutputStream()
val quality = 10
bitmapImage.compress(Bitmap.CompressFormat.JPEG, quality, bos)
val pixels = bos.toByteArray()

I really don't understand what's happening, as the same code produces different results whether I run it in the app or in a test...

EDIT

When running this in instrumented tests, everything works well. I would still like to understand why drawables are not obtained in unit test though.

like image 358
Baptiste Amato Avatar asked May 04 '26 00:05

Baptiste Amato


1 Answers

From what I can tell this is caused by the Robolectric Shadow implementation of BitmapFactory which doesn't actually open a resource, but just sets that the Bitmap was "created" by that resource. It is a stub implementation that doesn't actually do any work.

When Robolectric sees an object that has a Robolectric Shadow implementation, it uses the Shadow implementation instead of the real object. For more detailed information on how shadows work see the Robolectric Shadows documentation.

like image 175
Caitlin Avatar answered May 06 '26 16:05

Caitlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!