步骤
一、新建一个类,把截图存在指定路径中
public class ScreenShotUtil {
public static Logger logger = Logger.getLogger(ScreenShotUtil.class);
public static File saveScreenShot(){
File file = driver.getScreenshotAs(OutputType.FILE);
//把原始的file对象保存到图片文件中
//文件名字中加上时间戳 yyyy-MM-dd HH-mm-ss
SimpleDateFormat df = new SimpleDateFormat(“yyyyMMdd-HHmm-ss”);// 设置日期格式
String timeStamp = df.format(new Date());
File destFile = new File(System.getProperty(“user.dir”) +"\target\ScreenShot\"+"_"+ timeStamp+".png");
try {
logger.info(“拷贝文件失败截图到指定目录【D:\workspace2\compny-app\target\ScreenShot\” + timeStamp+".png" +"】");
FileUtils.copyFile(file, destFile);
} catch (IOException e) {
e.printStackTrace();
}
return destFile;
}
}
二、新建一个类实现IHookable接口,重写run方法,作用是把出现异常的方法的图片附到Allure报表中
public class AllureReporterListener implements IHookable{
@Override
public void run(IHookCallBack callBack, ITestResult testResult) {
// 执行test方法, 执行具体的测试函数(@Test注解标注的方法)
callBack.runTestMethod(testResult);
//如果出现异常
if(testResult.getThrowable() != null){
//调用截图方法
try {
takeScreenShot(testResult.getMethod().getMethodName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//把生成的截图方法作为附件贴到Allure报表中 报告添加附件
@Attachment(value = “Failure in method {0}” , type = “image/png”)
private byte[] takeScreenShot(String methodName) throws Exception {
File screenshot = ScreenShotUtil.saveScreenShot();
//将文件File转换成byte数组
return Files.toByteArray(screenshot);
}
}