Reputation: 637
I'm new in Android Testing. I'm using UIAutomator to make some Black-Box testing. I would like to take a screenshot each time a test fails. I tried to use the TestWatcher
class by adding a Rule in my test class. But, it doesn't work. I guess we cannot use the @Rule
annotation when using UIAutomator.
There are lots of related topics for Espresso but I didn't find anything for UIAutomator.
Does anyone have a method to solve my issue?
Thanks!
Upvotes: 1
Views: 923
Reputation: 6160
Yes, you can do it in this way:
@RunWith(AndroidJUnit4.class)
public class TestClass {
@Rule
public ScreenshotTakingRule rule = new ScreenshotTakingRule();
@Test
public void yourTest() {
}
}
and
/**
* Junit rule that takes a screenshot when a test fails.
*/
public class ScreenshotTakingRule extends TestWatcher {
@Override
protected void failed(Throwable e, Description description) {
Log.d(TAG, "taking screenshot..." + description.getMethodName());
takeScreenshot(description.getMethodName());
}
private void takeScreenshot(String screenShotName) {
ScreenCapture screenCapture = Screenshot.capture();
try {
screenCapture.setName(screenShotName);
Set<ScreenCaptureProcessor> processorSet = new HashSet<>();
processorSet.add(new SimpleNameScreenCaptureProcessor());
screenCapture.process(processorSet);
} catch (IOException ex) {
Log.d(TAG, "error while taking screenshot " + ex.getMessage());
}
}
}
Upvotes: 1