Skip to content

Recipe Take screenshots

Nico Küchler edited this page Apr 10, 2016 · 14 revisions

Take screenshot

Since Espresso Macchiato 0.4

You can take a screenshot every time.

EspScreenshootTool.takeWithName("short description");

With [EspFindTestClassFunction](Test Base EspFindTestClassFunction) can you access the current test class and method name.

StackTraceElement testClass = EspFindTestClassFunction.apply(Thread.currentThread().getStackTrace());
String className = testClass.getClassName().substring(testClass.getClassName().lastIndexOf(".") + 1);
String methodName = testClass.getMethodName();

See also

  • [EspScreenshotTool](Tool EspScreenshotTool)
  • [EspFindTestClassFunction](Test Base EspFindTestClassFunction)

Take screenshot when test fails

Since Espresso Macchiato 0.4

Use a custom failure handler when a test fails and take a screenshot from the current situation.

Note: Our [EspressoTestBase](Test Base EspressoTestBase) class takes already a screenshot when test failed.

public class CustomFailureHandler implements FailureHandler {
    private final FailureHandler delegate;

    public CustomFailureHandler(Context targetContext) {
        delegate = new DefaultFailureHandler(targetContext);
    }

    @Override
    public void handle(Throwable error, Matcher<View> viewMatcher) {
        try {
            StackTraceElement testClass = EspFindTestClassFunction.apply(Thread.currentThread().getStackTrace());
            String className = testClass.getClassName().substring(testClass.getClassName().lastIndexOf(".") + 1);
            String methodName = testClass.getMethodName();

            ScreenShot.takeWithName("Failed-" + className + "." + methodName);
        } catch (Exception e) {
            Log.e("EspressoMacchiato", "Could not create an image of the current screen.", e);
        }

        delegate.handle(error, viewMatcher);
    }
}

and register your custom error handler

@Before
public void setupEspresso() {
    Espresso.setFailureHandler(new CustomFailureHandler(getActivity()));
}

See also

Screenshots on device

pull screenshots

adb pull /data/data/${applicationId}/files/test-screenshots .

delete screenshots

adb shell rm /data/data/${applicationId}/files/test-screenshots/*