How to take screenshot at the point where test fail in Espresso?

后端 未结 6 1319
花落未央
花落未央 2021-01-04 05:59

I am looking for a way to take a screenshot of device after test failed and before get closed.

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 06:46

    Easiest way that I found:

    @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));
      }
    };
    

提交回复
热议问题