I am looking for a way to take a screenshot of device after test failed and before get closed.
Another improvement to previous answers. I'm using the experimental Screenshot API
public class ScreenshotTestRule extends TestWatcher {
@Override
protected void failed(Throwable e, Description description) {
super.failed(e, description);
takeScreenshot(description);
}
private void takeScreenshot(Description description) {
String filename = description.getTestClass().getSimpleName() + "-" + description.getMethodName();
ScreenCapture capture = Screenshot.capture();
capture.setName(filename);
capture.setFormat(CompressFormat.PNG);
HashSet processors = new HashSet<>();
processors.add(new CustomScreenCaptureProcessor());
try {
capture.process(processors);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've created CustomScreenCaptureProcessor because BasicScreenCaptureProcessor uses /sdcard/Pictures/ folder and I encountered IOExceptions on some devices when creating the folder/image. Please note that you need to place your processor in the same package
package android.support.test.runner.screenshot;
public class CustomScreenCaptureProcessor extends BasicScreenCaptureProcessor {
public CustomScreenCaptureProcessor() {
super(
new File(
InstrumentationRegistry.getTargetContext().getExternalFilesDir(DIRECTORY_PICTURES),
"espresso_screenshots"
)
);
}
}
Then, in your base Espresso test class just add
@Rule
public ScreenshotTestRule screenshotTestRule = new ScreenshotTestRule();
If you wish to use some protected folder, this did the trick on an emulator, tho it didn't work on a physical device
@Rule
public RuleChain screenshotRule = RuleChain
.outerRule(GrantPermissionRule.grant(permission.WRITE_EXTERNAL_STORAGE))
.around(new ScreenshotTestRule());