Another improvement to previous answers. I am using an experimental API screenshot
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<ScreenCaptureProcessor> processors = new HashSet<>(); processors.add(new CustomScreenCaptureProcessor()); try { capture.process(processors); } catch (IOException e) { e.printStackTrace(); } } }
I created CustomScreenCaptureProcessor because BasicScreenCaptureProcessor uses the / sdcard / Pictures / folder and I encountered an IOException on some devices when creating the folder / image. Please note that you need to put 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 test class, espresso just add
@Rule public ScreenshotTestRule screenshotTestRule = new ScreenshotTestRule();
If you want to use some kind of protected folder, this helped the emulator, but it didn’t work on the physical device.
@Rule public RuleChain screenshotRule = RuleChain .outerRule(GrantPermissionRule.grant(permission.WRITE_EXTERNAL_STORAGE)) .around(new ScreenshotTestRule());
source share