文章目录
一、简述
使用java(selenium)做自动化测试,使用testNg框架进行管理。但是生成的测试报告不够美观。网上都用ExtentTestNGIReport代替testNg中的报告。因为是UI自动化,所以需要进行截图了。这里完成了截图放进测试报告中,方便查看。效果图如下,点击图片可进行放大。
二、实现过程
1.ExtentTestNGIReport配置jar包(pom.xml)
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.1</version>
</dependency>
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>testng-extentsreport</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.6</version>
</dependency>
2.截图方法
(1)截图方法使用的是TestListenerAdapter中的用例失败截图方式,需要改写下。代码如下:
package com.Extent;
import com.aventstack.extentreports.ExtentReporter;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
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 String 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);
//把截图拷贝到自定义的目录
String currentPath = System.getProperty("user.dir");
String imgfile = currentPath+"\\test-output\\"+fileName;
FileUtils.copyFile(srcFile, new File(imgfile));
return "..\\test-output\\"+fileName;
/**
* 注意截图存放路径先不要随意修改,否则会影响报告中图片的显示。
* 当然如果你会调试,可以自定义设置。
*/
}
}
(2)重要:driver
测试用例中的driver传入的截图方法中。dr是你自己的driver驱动,此处一定要填写。
(3)xml配置文件中添加监听该类,运行xml文件后,可以看到用例失败的截图生成在test-output文件夹下,成功后再进行下一步。
<listeners>
<listener class-name="com.Extent.TestngListener"/>
</listeners>
3.在测试报告中引入图片文件
重写ExtentTestNgFormatter类,在这个类中可以放图片的文件路径,进行在测试报告中展示。思路就是图片的路径放进这个类的方法中。修改的地方如图所示
代码如下:
package com.Extent;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.vimalselvam.testng.EmailReporter;
import com.vimalselvam.testng.NodeName;
import com.vimalselvam.testng.SystemInfo;
import com.vimalselvam.testng.listener.ExtentTestNgFormatter;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyExtentTestNgFormatter extends ExtentTestNgFormatter {
private static final String REPORTER_ATTR = "extentTestNgReporter";
private static final String SUITE_ATTR = "extentTestNgSuite";
private ExtentReports reporter;
private List<String> testRunnerOutput;
private Map<String, String> systemInfo;
private ExtentHtmlReporter htmlReporter;
private static ExtentTestNgFormatter instance;
public MyExtentTestNgFormatter() {
setInstance(this);
testRunnerOutput = new ArrayList<>();
// reportPath 报告路径
String reportPathStr = System.getProperty("reportPath");
File reportPath;
try {
reportPath = new File(reportPathStr);
} catch (NullPointerException e) {
reportPath = new File(TestNG.DEFAULT_OUTPUTDIR);
}
if (!reportPath.exists()) {
if (!reportPath.mkdirs()) {
throw new RuntimeException("Failed to create output run directory");
}
}
// 报告名report.html
File reportFile = new File(reportPath, "report.html");
// 邮件报告名emailable-report.html
File emailReportFile = new File(reportPath, "emailable-report.html");
htmlReporter = new ExtentHtmlReporter(reportFile);
EmailReporter emailReporter = new EmailReporter(emailReportFile);
reporter = new ExtentReports();
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
htmlReporter.config().setDocumentTitle("UI自动化测试报告");
htmlReporter.config().setReportName("UI自动化测试报告");
reporter.attachReporter(htmlReporter, emailReporter);
}
public static ExtentTestNgFormatter getInstance() {
return instance;
}
private static void setInstance(ExtentTestNgFormatter formatter) {
instance = formatter;
}
public Map<String, String> getSystemInfo() {
return systemInfo;
}
public void setSystemInfo(Map<String, String> systemInfo) {
this.systemInfo = systemInfo;
}
public void onStart(ISuite iSuite) {
if (iSuite.getXmlSuite().getTests().size() > 0) {
ExtentTest suite = reporter.createTest(iSuite.getName());
String configFile = iSuite.getParameter("report.config");
if (!Strings.isNullOrEmpty(configFile)) {
htmlReporter.loadXMLConfig(configFile);
}
String systemInfoCustomImplName = iSuite.getParameter("system.info");
if (!Strings.isNullOrEmpty(systemInfoCustomImplName)) {
generateSystemInfo(systemInfoCustomImplName);
}
iSuite.setAttribute(REPORTER_ATTR, reporter);
iSuite.setAttribute(SUITE_ATTR, suite);
}
}
private void generateSystemInfo(String systemInfoCustomImplName) {
try {
Class<?> systemInfoCustomImplClazz = Class.forName(systemInfoCustomImplName);
if (!SystemInfo.class.isAssignableFrom(systemInfoCustomImplClazz)) {
throw new IllegalArgumentException("The given system.info class name <" + systemInfoCustomImplName +
"> should implement the interface <" + SystemInfo.class.getName() + ">");
}
SystemInfo t = (SystemInfo) systemInfoCustomImplClazz.newInstance();
setSystemInfo(t.getSystemInfo());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
public void onFinish(ISuite iSuite) {
}
public void onTestStart(ITestResult iTestResult) {
}
public void onTestSuccess(ITestResult iTestResult) {
}
public void onTestFailure(ITestResult iTestResult) {
}
public void onTestSkipped(ITestResult iTestResult) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
}
public void onStart(ITestContext iTestContext) {
ISuite iSuite = iTestContext.getSuite();
ExtentTest suite = (ExtentTest) iSuite.getAttribute(SUITE_ATTR);
ExtentTest testContext = suite.createNode(iTestContext.getName());
iTestContext.setAttribute("testContext", testContext);
}
public void onFinish(ITestContext iTestContext) {
ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
if (iTestContext.getFailedTests().size() > 0) {
testContext.fail("Failed");
} else if (iTestContext.getSkippedTests().size() > 0) {
testContext.skip("Skipped");
} else {
testContext.pass("Passed");
}
}
public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
if (iInvokedMethod.isTestMethod()) {
ITestContext iTestContext = iTestResult.getTestContext();
ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
ExtentTest test = testContext.createNode(iTestResult.getName(), iInvokedMethod.getTestMethod().getDescription());
iTestResult.setAttribute("test", test);
}
}
public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
if (iInvokedMethod.isTestMethod()) {
ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
List<String> logs = Reporter.getOutput(iTestResult);
for (String log : logs) {
test.info(log);
}
int status = iTestResult.getStatus();
if (ITestResult.SUCCESS == status) {
test.pass("Passed");
} else if (ITestResult.FAILURE == status) {
test.fail(iTestResult.getThrowable());
ITestResult tr = Reporter.getCurrentTestResult();
//测试用例错误的时候,截图,把截图放进报告里面。
try {
TestngListener testngListener = new TestngListener();
// testngListener.onTestFailure(tr);
test.addScreenCaptureFromPath(testngListener.takeScreenShot(tr));
}catch (IOException e){
e.printStackTrace();
}
} else {
test.skip("Skipped");
}
for (String group : iInvokedMethod.getTestMethod().getGroups()) {
test.assignCategory(group);
}
}
}
public void addScreenCaptureFromPath(ITestResult iTestResult, String filePath) throws IOException {
ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
test.addScreenCaptureFromPath(filePath);
}
public void addScreenCaptureFromPath(String filePath) throws IOException {
ITestResult iTestResult = Reporter.getCurrentTestResult();
Preconditions.checkState(iTestResult != null);
ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
test.addScreenCaptureFromPath(filePath);
}
public void setTestRunnerOutput(String message) {
testRunnerOutput.add(message);
}
public void generateReport(List<XmlSuite> list, List<ISuite> list1, String s) {
if (getSystemInfo() != null) {
for (Map.Entry<String, String> entry : getSystemInfo().entrySet()) {
reporter.setSystemInfo(entry.getKey(), entry.getValue());
}
}
reporter.setTestRunnerOutput(testRunnerOutput);
reporter.flush();
}
public void addNewNodeToTest() {
addNewNodeToTest(NodeName.getNodeName());
}
public void addNewNodeToTest(String nodeName) {
addNewNode("test", nodeName);
}
public void addNewNodeToSuite() {
addNewNodeToSuite(NodeName.getNodeName());
}
public void addNewNodeToSuite(String nodeName) {
addNewNode(SUITE_ATTR, nodeName);
}
private void addNewNode(String parent, String nodeName) {
ITestResult result = Reporter.getCurrentTestResult();
Preconditions.checkState(result != null);
ExtentTest parentNode = (ExtentTest) result.getAttribute(parent);
ExtentTest childNode = parentNode.createNode(nodeName);
result.setAttribute(nodeName, childNode);
}
public void addInfoLogToNode(String logMessage) {
addInfoLogToNode(logMessage, NodeName.getNodeName());
}
public void addInfoLogToNode(String logMessage, String nodeName) {
ITestResult result = Reporter.getCurrentTestResult();
Preconditions.checkState(result != null);
ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
test.info(logMessage);
}
public void failTheNode(Throwable t) {
failTheNode(NodeName.getNodeName(), t);
}
public void failTheNode(String nodeName, Throwable t) {
ITestResult result = Reporter.getCurrentTestResult();
Preconditions.checkState(result != null);
ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
test.fail(t);
}
public void failTheNode(String logMessage) {
failTheNode(NodeName.getNodeName(), logMessage);
}
public void failTheNode(String nodeName, String logMessage) {
ITestResult result = Reporter.getCurrentTestResult();
Preconditions.checkState(result != null);
ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
test.fail(logMessage);
}
}
4.xml配置文件中添加监听该类
监听新写的类,注意执行xml文件启动用例。否则不会有截图和报告产生。
<listeners>
<!--<listener class-name="com.Extent.TestngListener"/>-->
<listener class-name="com.Extent.MyExtentTestNgFormatter"/>
</listeners>
我的TestngListener类 和MyExtentTestNgFormatter类存在的位置。在report.html中可以看到错误用例的截图。