我有一个程序,可以从保存在存储区域中的全尺寸图像创建缩略图。我正在尝试使用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();
}
}
感谢您的帮助。如果我做错了,请原谅。