自动化测试系列(第十一天)—— 测试用例(截图版)
来写一个selenium+testng+reportng测试报告显示测试失败截图的测试用例
参考文章
reportng定制修改
失败后操作
//用例结束的时候判断结果是否失败
@AfterMethod(alwaysRun = true)
public void afterMethod(ITestResult result) throws Exception {
if (!result.isSuccess())
catchExceptions(result);
}
//失败将设置的图片写入report
public void catchExceptions(ITestResult result) throws IOException {
if (!result.isSuccess()) {
//在testng的report默认路径test-output下的html文件夹中创建一个截图文件夹以存放截图
//截图放在这里把整个测试报告(test-output文件夹)单独打包发给别人查看也不会报错
File file = new File("test-output/html/snapshot");
Reporter.setCurrentTestResult(result);
Reporter.log(file.getAbsolutePath());
String filePath = file.getAbsolutePath();
String dest = result.getMethod().getRealClass().getSimpleName()+"."+result.getMethod().getMethodName();
String time = DateUtils.getCurrentDateTime2();
String picName=filePath+File.separator+dest+time +".png";
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File(picName));
String escapePicName="snapshot"+File.separator+dest+time+".png";
String openPicName=escapeString("snapshot"+File.separator+dest+time+".png");
//window.open()实现点击图片在新窗口显示大图,其中图片路径需要转义
String html="<img src='"+escapePicName+"' onclick='window.open(\""+openPicName+"\")'' hight='100' width='100'/>";
Reporter.log(html);
}
}
/**
* 替换字符串
* @param s 待替换string
* @return 替换之后的string
*/
public String escapeString(String s)
{
if (s == null)
{
return null;
}
StringBuilder buffer = new StringBuilder();
for(int i = 0; i < s.length(); i++)
{
buffer.append(escapeChar(s.charAt(i)));
}
return buffer.toString();
}
/**
* 将\字符替换为\\
* @param character 待替换char
* @return 替换之后的char
*/
private String escapeChar(char character)
{
switch (character)
{
case '\\': return "\\\\";
default: return String.valueOf(character);
}
}
这里我把时间工具类获取时间至毫秒的方法放一下,获取至毫秒就不用担心每分钟多次截图了
public static String getCurrentDateTime2() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(calendar.getTime());
}
待续
有问题请留言。