Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso test the camera intent when imageuri is passed as extra

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

like image 845
PK Gupta Avatar asked May 22 '17 13:05

PK Gupta


1 Answers

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());
like image 72
PK Gupta Avatar answered Nov 16 '22 01:11

PK Gupta