4

I am using Espresso for my UI Testing in my project. I want to take screen shot of each Activity(Screen). I am using ScreenShooter from GoogleCloudTestLab for taking screen shot.

   ScreenShotter.takeScreenshot("main_screen_2", getActivity());

But it only taking the screen shot of the 1st activity which i defined in my ActivityTestRule. How can I take other activity screen shot with in the same testcase.

BalaramNayak
  • 1,295
  • 13
  • 16

2 Answers2

2

My understanding is ActivityTestRule is designed to test only one Activity within the testcase so getActivity() will only return the activity that you specified in the ActivityTestRule.

To capture the screenshot, the library currently uses:

View screenView = activity.getWindow().getDecorView().getRootView(); screenView.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache()); screenView.setDrawingCacheEnabled(false);

(where activity is the activity the user passes us.)

So because the same activity is being given to takescreenshot, we are only able to capture that activity's view hierarchy at that time. Would you be able to split up your tests to test only one activity per testcase?

Also, we are currently exploring other ways to capture the screen and will add to this thread if we change this method.

Note: If you are using this library to run tests in Firebase Test Lab and you have a prefered way of capturing screenshots (instead of using the library), as long as they end up in the /sdcard/screenshots directory then they will be pulled and uploaded to the dashboard at the end of the test.

Emma Marsh
  • 21
  • 3
1

I had the same issue since my tests cover flows which span multiple activities. A helper method such as this one can be used to get a reference to the currently active (on top) activity:

/**
 * A helper method to get the currently running activity under test when a test run spans across multiple
 * activities. The {@link android.support.test.rule.ActivityTestRule} only returns the initial activity that
 * was started.
 */
public static final Activity getCurrentActivity(Instrumentation instrumentation)
{
    final Activity[] currentActivity = new Activity[1];
    instrumentation.runOnMainSync(new Runnable()
    {
        public void run()
        {
            Collection<Activity> resumedActivities =
                ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED);
            if (resumedActivities.iterator().hasNext())
            {
                currentActivity[0] = resumedActivities.iterator().next();
            }
        }
    });
    return currentActivity[0];
}

Pass it getInstrumentation() from within your test and you should be good to go.

Jerry Brady
  • 3,050
  • 24
  • 30