【发布时间】:2019-03-28 23:52:51
【问题描述】:
我有一个程序可以从存储区中保存的全尺寸图像创建缩略图。我正在尝试使用 mockito 测试该功能,但它给了我以下错误:
java.lang.RuntimeException:android.graphics.BitmapFactory 中的方法 decodeFile 未被模拟
//已解决(更新代码)
我第一次使用 mockito 运行单元测试,有人可以建议我做错了什么(我知道肯定会这样做)。我也在使用 ExifInterface 来提取与图像关联的元数据,但它再次给了我同样的错误: 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();
}
}
感谢你们的帮助。如果我做错了什么,请原谅。
【问题讨论】:
标签: android unit-testing mockito powermockito