Tips and Tricks: Taking Screenshots with Google Espresso 1.x or v2.0

Bitbar, the mobile devops company. Logo, large

Dear Testdroiders,

It’s awesome to see many of you using Google’s Espresso (or Espresso v2.0) with our Testdroid Cloud devices. We do get some questions every now and then about the ability to take screenshots during the test so I’ll share this brief example to showcase an example function call that can be used as a part of your test.

Screen Shot 2015-05-13 at 10.52.13 AM

As Espresso v1.x or v2.0 doesn’t have internal function call dedicated for screenshot capturing the user must use or implement something for themselves. We’ll take a look at basic example of this in this blog. Also, it recommended that if you are starting from the scratch and/or you don’t have prior experience with Espresso v1.x/Espresso v2.0 please check out the installation/setup instructions first.

NOTE! Remember that if you implement your own screenshot taking functions you should store the captured screenshots under /sdcard/test-screenshots/ to ensure those get shown in Testdroid Cloud Results view -> Screenshots widget. If you want to configure the path where screenshots are written this can be done during the Step #4: Advanced options when starting a new testrun at Testdroid Cloud:

Screen Shot 2015-05-13 at 12.01.24 PM

Allright, let’s look at the code example for a simple screenshot taking function with Java:

import java.io.File;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.view.View;
import android.os.Environment;

public static void takeScreenshot(String name, Activity activity)
{

    // In Testdroid Cloud, taken screenshots are always stored
    // under /test-screenshots/ folder and this ensures those screenshots
    // be shown under Test Results
    String path = 
        Environment.getExternalStorageDirectory().getAbsolutePath() + "/test-screenshots/" + name + ”.png”;

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

    OutputStream out = null;
    File imageFile = new File(path);

    try {
        out = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
    } catch (FileNotFoundException e) {
        // exception
    } catch (IOException e) {
        // exception
    } finally {

        try {
            if (out != null) {
                out.close();
            }

        } catch (Exception exc) {
        }

    }
}

In addition to get this working and avoid FileNotFoundException each and every time you call this function, you should check that Android manifest file includes the following line:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

To call the function you just add the following line with proper classname reference to your Espresso test:

<classname>.takeScreenshot("screenshot-001", getActivity());


Note!
 If you use the same name for file to be written (captured screenshot) the older one gets rewritten. Make sure whenever you call this function you have a new name for the captured screenshot file.

Screen Shot 2015-05-13 at 10.36.06 AM

In order to understand the full instructions how to use Testdroid Cloud devices with Espresso v1.x or Espresso v2.0 please check out those step-by-step instructions. Also, you can now run your tests directly from Android Studio using Testdroid Gradle plugin. This awesome plugin eliminates the need for any manual effort in order to build and get your APK up and running on physical devices.

Happy Espresso-Testing!

  • Mirek Stanek

    Hey, does your solution work with Dialogs, Toasts and all other floating views? I’m not sure, but Spoon also uses DecorView and it can capture only activity view, which sometimes is not enough.

    • David Developer

      Yeah, it should work as it grabs everything with getWindow().getDecorView().getRootView(). But notifications may be out of those scope – and generally for those there are better solutions.

  • lechuckcaptain

    I’m getting the following exception. Am I doing something wrong? Can you confirm that your solution works without issues with latest Espresso release (2.2)?

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

    • Ville-Veikko Helppi

      Maybe one of these would fix this problem:

      Runnable runnable = new Runnable() {
      public void run() {
      // take screenshot here
      }
      }

      // 1st option
      new Thread(runnable).start();

      // 2nd option
      getActivity().runOnUiThread(runnable);

      // 3rd option
      getInstrumentation().runOnMainSync(runnable);

      If you have success with these, please let us know 🙂

  • Screenshots directory option is not available. I am not seeing it anywhere on my dashboard!

    • Ville-Veikko Helppi

      Hey – found a typo on this blog, but did you define screenshot name extension in your test script? (e.g. /sdcard/test-screenshots/screenshot-001.png)

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close