大家好,我想在扩展报告和失败测试用例的屏幕截图中实现我通过的测试用例的日志



这是我的扩展数据块管理器类,我在其中实现了扩展数据块报告,版本是 3.1.5

package resources;
import org.openqa.selenium.Platform;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class ExtentManager {
private static ExtentReports extent;
private static Platform platform;
private static String reportFileName = "ExtentReports-Version3-Test-Automaton-Report.html";
private static String macPath = System.getProperty("user.dir")+ "/TestReport";
private static String windowsPath = System.getProperty("user.dir")+ "\TestReport";
private static String macReportFileLoc = macPath + "/" + reportFileName;
private static String winReportFileLoc = windowsPath + "\" + reportFileName;
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static ExtentReports createInstance() {
platform = getCurrentPlatform();
String fileName = getReportFileLocation(platform);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
return extent;
}
//Select the extent report file location based on platform
private static String getReportFileLocation (Platform platform) {
String reportFileLocation = null;
switch (platform) {
case MAC:
reportFileLocation = macReportFileLoc;
createReportPath(macPath);
System.out.println("ExtentReport Path for MAC: " + macPath + "n");
break;
case WINDOWS:
reportFileLocation = winReportFileLoc;
createReportPath(windowsPath);
System.out.println("ExtentReport Path for WINDOWS: " + windowsPath + "n");
break;
default:
System.out.println("ExtentReport path has not been set! There is a problem!n");
break;
}
return reportFileLocation;
}
//Create the report path if it does not exist
private static void createReportPath (String path) {
File testDirectory = new File(path);
if (!testDirectory.exists()) {
if (testDirectory.mkdir()) {
System.out.println("Directory: " + path + " is created!" );
} else {
System.out.println("Failed to create directory: " + path);
}
} else {
System.out.println("Directory already exists: " + path);
}
}
//Get current platform
private static Platform getCurrentPlatform () {
if (platform == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
platform = Platform.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
platform = Platform.LINUX;
} else if (operSys.contains("mac")) {
platform = Platform.MAC;
}
}
return platform;
}
}

我的测试侦听器类代码是

package resources;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
public class TestListener implements ITestListener {
//Extent Report Declarations
private static ExtentReports extent = ExtentManager.createInstance();
private static ThreadLocal<ExtentTest> test = new ThreadLocal<>();
@Override
public synchronized void onStart(ITestContext context) {
System.out.println("Extent Reports Version 3 Test Suite started!");
}
@Override
public synchronized void onFinish(ITestContext context) {
System.out.println(("Extent Reports Version 3  Test Suite is ending!"));
extent.flush();
}
@Override
public synchronized void onTestStart(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " started!"));
ExtentTest extentTest = extent.createTest(result.getMethod().getMethodName(),result.getMethod().getDescription());
test.set(extentTest);
}
@Override
public synchronized void onTestSuccess(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " passed!"));
test.get().pass("Test passed");
}
@Override
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
}
@Override
public synchronized void onTestSkipped(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " skipped!"));
test.get().skip(result.getThrowable());
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
System.out.println(("onTestFailedButWithinSuccessPercentage for " + result.getMethod().getMethodName()));
}
}

我的记录器文件是

package logger;
import java.io.IOException;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
/**
* contains all the methods to show the logs on console 
* and save the logs in LogFile.txt of each run.
*/
public class Log
{
private static final Logger LOGGER = Logger.getLogger("logger");
private static PatternLayout layout = new PatternLayout("%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n");
private static FileAppender appender;
private static ConsoleAppender consoleAppender;
static
{
try 
{
consoleAppender = new ConsoleAppender(layout, "System.out");
appender= new FileAppender(layout,"LogFile.txt",true);
}
catch (IOException exception) 
{
exception.printStackTrace();
}
}
/**
* method to display errors in log.
* @param className name of class in which error occurred.
* @param methodName name of method in which error occurred.
* @param exception stack trace of exception
*/
public static void logError (String className,String methodName,String exception) 
{   
LOGGER.addAppender(appender);
LOGGER.setLevel((Level) Level.INFO);
LOGGER.info("ClassName :"+className);
LOGGER.info("MethodName :"+methodName );
LOGGER.info("Exception :" +exception);
LOGGER.info("-----------------------------------------------------------------------------------");
}
/**
* method to display information in logs
* @param message message to be displayed
*/
public static void info(String message){
consoleAppender.setName("Console");
LOGGER.addAppender(consoleAppender);
LOGGER.addAppender(appender);
LOGGER.setLevel((Level) Level.INFO);
LOGGER.info(message);
}
}

我想在盘区报告中进行更改,以便在测试用例通过时在盘区报告中显示日志,并希望在盘区报告中为失败的测试用例添加屏幕截图,请建议我必须在何处进行更改。上面的两个代码都正常工作。

要在范围报告中添加失败测试的屏幕截图,请使用以下代码:

@Override
public void onTestFailure(ITestResult result) {
test.get().fail("Test Failed"+result.getThrowable());
WebDriver driver = null;
Object testObj = result.getInstance(); //Instance of test failed
Class testClass = result.getTestClass().getRealClass(); //Class in which test failed

try {
Field driverField = testClass.getDeclaredField("driver"); //get the driver field of failed test class
driverField.setAccessible(true); // if driver field is private
driver = (WebDriver)driverField.get(testObj); // here you get the driver of failed test method
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
try {
test.get().addScreenCaptureFromPath(TestUtil.getScreenshotPath(driver, result.getMethod().getMethodName()), result.getMethod().getMethodName()); // this method will add the screenshot for failed test in extent report
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

注意:这里TestUtil是存在getScreenshotPath方法的实用程序类。调用该方法,该方法应返回项目中失败屏幕截图的路径。代码如下:

public static String getScreenshotPath(WebDriver driver, String testcaseName) throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String destPath = System.getProperty("user.dir")+ "\screenshots\" + testcaseName +System.currentTimeMillis() + ".png";
File destFile= new File(destPath);
FileUtils.copyFile(scrFile, destFile);
return destPath;
}

希望对:)有所帮助

最新更新