我正在开发我的Android应用程序中的一项新功能,用户可以按下按钮来启动相机,拍照并保存到应用程序的本地数据库中以供使用。这是用户单击该按钮时调用的方法及其用于创建文件的辅助方法(在Java中):
private void capturePicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.frischlymade.spoken.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PIC);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentImagePath = image.getAbsolutePath();
return image;
}
我现在正在学习如何测试Android应用程序,Robolectric似乎是进行单元测试的好工具。遵循文档和首次用户测试
@Test
public void clickingLogin_shouldStartLoginActivity() {
WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
activity.findViewById(R.id.login).performClick();
Intent expectedIntent = new Intent(activity, LoginActivity.class);
Intent actual = shadowOf(RuntimeEnvironment.application).getNextStartedActivity();
assertEquals(expectedIntent.getComponent(), actual.getComponent());
}
我为我的方法编写了此测试(在Kotlin中):
@Test fun clickingTake_shouldStartCamera() {
val activity: AddCategoryActivity = Robolectric.setupActivity(AddCategoryActivity::class.java)
activity.findViewById<MaterialButton>(R.id.item_take_pic_btn).performClick()
val expected = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val actual = shadowOf(RuntimeEnvironment.application).nextStartedActivity
assertEquals(expected.component, actual.component)
}
但是,当我运行测试时,测试失败,结果为“ actual不能为null”。所以我知道出了点问题,与示例的主要区别是我在显式上使用了隐式意图。我也正在开始暗示结果的意图,这也可能会影响事物。我不知道为什么我得到错误。我如何修改它以适用于隐式意图?还是我应该以其他方式这样做?