如何模拟BitmapFactory:方法decodeFile

时间:2018-10-24 14:09:19

标签: android unit-testing mockito powermockito

我有一个程序,可以从保存在存储区域中的全尺寸图像创建缩略图。我正在尝试使用Mockito测试该功能,但是它给了我以下错误:

java.lang.RuntimeException:android.graphics.BitmapFactory中的方法解码文件未模拟

//已解决(更新代码)

我第一次使用Mockito运行单元测试,请问有人提出我做错了什么(我肯定知道做错了)。我还使用ExifInterface提取与图像关联的metaData,但它再次给了我相同的错误: java.lang.RuntimeException:未模拟android.media.ExifInterface中的方法getAttribute。

这里是MainActivity类:(我正在运行该方法的地方)。

 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);
        }

    }

我的测试班:

 @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();
    }
    }

感谢您的帮助。如果我做错了,请原谅。

1 个答案:

答案 0 :(得分:2)

您可以:

  • 使用超级模拟来模拟静态方法解码文件。查看有关码头的here
  • 将位图解码逻辑提取到单独的类中,提取接口并提供 在运行时实现不同的实现。