Search code examples
androidunit-testingmockitopowermockito

How to mock BitmapFactory: Method decodeFile


I have a program which creates thumbnail image from a full size image saved in the storage area . I am trying to test that functionality using mockito but it gives me the following error:

java.lang.RuntimeException: Method decodeFile in android.graphics.BitmapFactory not mocked

//Solved(Updated code)

I am running unit tests using mockito for the first time, Could someone please suggest what I am doing wrong(which I know definitely doing). I am also using ExifInterface to extract the metaData associated with the image but it is giving me the same error again: java.lang.RuntimeException: Method getAttribute in android.media.ExifInterface not mocked.

Here is the MainActivity class :(where I am running the method).

 public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initValue();
        }

        public void initValue()
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap thumbnail = createThumbnailFromBitmap("/storage/emulator/0/demo/abcd", 100, 100);

 try {
            ExifInterface exifInterface = new ExifInterface("/storage/emulator/0/demo/abcd");
            String jsonData = exifInterface.getAttribute("UserComment");

            try {
                JSONObject rootJson = new JSONObject(jsonData);
                dateList.add(rootJson.getString("captured"));

            }

            catch(JSONException e)
            {
            }
        }
        catch(Exception e)
        {
            System.out.println("exception "+e);
        }
        }

        private Bitmap createThumbnailFromBitmap(String filePath, int width, int height){
            return ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filePath), width, height);
        }

    }

My test class:

 @RunWith(PowerMockRunner.class)
@PrepareForTest({BitmapFactory.class ,ThumbnailUtils.class})
    public class initValueTest {


        @Mock
        private Bitmap bitmap;


        @Test
    public void initValueTest()
    {
        PowerMockito.mockStatic(BitmapFactory.class);
        PowerMockito.mockStatic(ThumbnailUtils.class);
        when(BitmapFactory.decodeFile(anyString())).thenReturn(bitmap);
        MainActivity mainActivity =  new MainActivity();
        mainActivity.initValue();
    }
    }

Thanks for your help guys. Please excuse if I am doing anything wrong.


Solution

  • You can either:

    • Use power mock to mock static method decodeFile. See docks about it here
    • Extract bitmap decoding logic to a separate class, extract interface and provide different implementation at run time.