Bitmap.CreateBitmap return null in JUnit Testing Android Studio

4.7k Views Asked by At

I need to create a fake bitmap image for testing (JUnit Test) my personal add and get methods of a custom LinkedList but the Bitmap.createBitmap return the error:

java.lang.RuntimeException: Method createBitmap in android.graphics.Bitmap not mocked.

This is the code of my JUnitTest:

public class TicketsIteratorTest {

    Bitmap img_Bmp;
    TicketsIterator<Bitmap> TicketsList = new TicketsIterator();

    /*
     * Test for the add e get methods, check if the element just insert it's the same of the one just extract.
     */
    @Test
    public void Add_n_Get() throws Exception {
        int i = 0, numIMG = 100;
        Bitmap[] IMG_Generated;
        IMG_Generated = new Bitmap[numIMG];

        // Generate numIMG of imagine to insert into the Iterator and it save each one of it into an
        // Bitmap array usefull for testing of the get method
        while (i <= numIMG) {
            // Generation of the fake Ticket Bitmap
            try {
                img_Bmp = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

                IMG_Generated[i] = img_Bmp;

            } catch (Exception e) {
                // Print the cause of the error just generated
                e.getCause().printStackTrace();
            }

            // Addition of the imagine just created
            TicketsList.add(img_Bmp);

            i++;
        }

        // Test if the imagine inserted it is correct
        while (i <= numIMG) {
            assertTrue(IMG_Generated[i] == TicketsList.get(IMG_Generated[i]));
            i++;
        }
    }

Thank you for the help.

3

There are 3 best solutions below

0
Dariusz Wiechecki On

Are you using this in regular unit tests or in Android Tests? If you are calling this from normal unit test, android classes will be replaced with empty/null implementation. This means call to Bitmap.createBitmap() will just always return null without even checking yours parameters etc.

I had similar issue in the past with Bitmap and with Base64OutputStream. Everything seems to be working perfectly fine, except nothing is happening behind ;) Whenever you will see similar behaviour check if class is not from Android framework - that will be most probably the reason for problems.

I hope that was that and I could help you. I am using PowerMock and just mocked Bitmap class to return Bitmap mock instance in my case.

best regards,

Dariusz Wiechecki

0
anand krish On

Instrumentation Test case will work in this case, Unit test case will return null (fail) for bitmap because it's related to Android framework.

I faced similar type of issue while reading a file from connected device (Mobile) filepath in Unit test case, it couldn't read but it works in Instrumentation Test

0
AntPachon On

You can use the kotlin extension toBitmap() from a drawable.

ContextCompat.getDrawable(context, R.drawable.x)?.toBitmap()