问题描述
我是Android测试的新手。我正在使用UIAutomator进行一些黑盒测试。每当测试失败时,我都想截图。我试图通过在测试类中添加规则来使用TestWatcher
类。但是,它不起作用。我想我们在使用UIAutomator时不能使用@Rule
注释。
Espresso有很多相关主题,但我没有为UIAutomator找到任何东西。
有人有办法解决我的问题吗?
谢谢!
解决方法
是的,您可以通过以下方式做到这一点:
@RunWith(AndroidJUnit4.class)
public class TestClass {
@Rule
public ScreenshotTakingRule rule = new ScreenshotTakingRule();
@Test
public void yourTest() {
}
}
和
/**
* 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());
}
}
}