I need to stub the camera intent by creating a image file at the path provided in the intent extra. Espresso can only respond with activityresult. Where can i perform the operation to create the file at passed path from intent extra.
Code for launching camera
File destination = new File(Environment.getExternalStorageDirectory(), "app_name" + System.currentTimeMillis() + ".jpg");
imageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".fileprovider", destination); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, AppConstants.REQUEST_CODE_CAMERA);
Code for stubbing intent in test
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, null);
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
Ismael answer is perfect. For those looking for solution in java, Here it is.
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(
new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
IntentCallback intentCallback = new IntentCallback() {
@Override
public void onIntentSent(Intent intent) {
if (intent.getAction().equals("android.media.action.IMAGE_CAPTURE")) {
try {
Uri imageUri = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
Context context = InstrumentationRegistry.getTargetContext();
Bitmap icon = BitmapFactory.decodeResource(
context.getResources(),
R.mipmap.ic_launcher);
OutputStream out = getTargetContext().getContentResolver().openOutputStream(imageUri);
icon.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
GenericUtility.handleException(e);
}
}
}
};
IntentMonitorRegistry.getInstance().addIntentCallback(intentCallback);
//Perform action here
onView(withId(R.id.tv_take_photo)).perform(click());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With