我在IReporter TestNG
中使用Selenium
界面,但是如何捕获屏幕截图并在范围报告中添加失败的测试用例?
请帮助我找到解决方法。
答案 0 :(得分:0)
下面是将失败的测试用例屏幕快照附加到范围报告的代码。
public class MyReporterClass implements IReporter { @Override public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) { //Iterating over each suite included in the test for (ISuite suite : suites) { //Following code gets the suite name String suiteName = suite.getName(); //Getting the results for the said suite Map<String, ISuiteResult> suiteResults = suite.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext tc = sr.getTestContext(); System.out.println("Passed tests for suite '" + suiteName + "' is:" + tc.getPassedTests().getAllResults().size()); System.out.println("Failed tests for suite '" + suiteName + "' is:" + tc.getFailedTests().getAllResults().size()); System.out.println("Skipped tests for suite '" + suiteName + "' is:" + tc.getSkippedTests().getAllResults().size()); } } } }
public class ExtentReportsClass{ public static String getScreenshot(WebDriver driver, String screenshotName) throws Exception { //below line is just to append the date format with the screenshot name to avoid duplicate names String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()); TakesScreenshot ts = (TakesScreenshot) driver; File source = ts.getScreenshotAs(OutputType.FILE); //after execution, you could see a folder "FailedTestsScreenshots" under src folder String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/"+screenshotName+dateName+".png"; File finalDestination = new File(destination); FileUtils.copyFile(source, finalDestination); //Returns the captured file path return destination; } }
@AfterMethod public void getResult(ITestResult result) throws IOException{ if(result.getStatus() == ITestResult.FAILURE){ logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName()); logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable()); //To capture screenshot path and store the path of the screenshot in the string "screenshotPath" String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName()); //To add it in the extent report logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath)); }else if(result.getStatus() == ITestResult.SKIP){ logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName()); }
<listeners> <listener class-name="packagename.MyReporterClass" /> </listeners>