转载自:https://blog.csdn.net/galen2016/article/details/70193684
重写Listener的onTestFailure方法
package com.kdzwy.practice;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class TestngListener extends TestListenerAdapter {
public static WebDriver driver;
@Override
public void onTestFailure(ITestResult tr) {
super.onTestFailure(tr);
try {
takeScreenShot(tr);
} catch (IOException e) {
e.printStackTrace();
}
}
public void takeScreenShot(ITestResult tr) throws IOException{
SimpleDateFormat smf = new SimpleDateFormat("MMddHHmmss") ;
String curTime = smf.format(new java.util.Date());
String fileName = tr.getName()+"_"+curTime+".png";
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//把截图拷贝到自定义的目录
FileUtils.copyFile(srcFile, new File("Report\FailureScreenShot\"+fileName));
}
}
使用TestngListener.class
第一种方式:添加Listener注解
第二种方式:在testng.xml里添加listeners标签
代码如下:
testng.xml如下:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1">
<test name="login">
<classes>
<class name="com.kdzwy.practice.BaiduDemo" />
</classes>
</test>
<listeners>
<listener class-name="com.kdzwy.practice.TestngListener" />
</listeners>
</suite>
运行
注意看我把代码里点击“百度一下”按钮的id写成了“su1”,所以该用例会运行失败,运行结果如下:
失败截图如下: