When running Espresso tests I wanted a way to save screenshots of the app under test whenever a test failed. This feature isn't currently supported and all of the solutions online seemed overly complex due to supporting older test tool versions, like manually parsing the stack trace for the method name. Ouch. If your tests are using a more recent version of JUnit and the AndroidJUnit4 runner, there is a much simpler way:

@Rule
public TestRule watcher = new TestWatcher() {
  @Override
  protected void failed(Throwable e, Description description) {
    // Save to external storage (usually /sdcard/screenshots)
    File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/screenshots/" + getTargetContext().getPackageName());
    if (!path.exists()) {
      path.mkdirs();
    }

    // Take advantage of UiAutomator screenshot method
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    String filename = description.getClassName() + "-" + description.getMethodName() + ".png";
    device.takeScreenshot(new File(path, filename));
  }
};

See the Testing Support Library.


Comments

comments powered by Disqus