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

问题描述 投票:0回答:1

这是我的 extent manger 类,我在这里实现了 extents 报告,版本是 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);
    }

}

我想对extents报告进行修改,以便在测试用例获得通过时,在extents报告中显示日志,并在extents报告中为失败的测试用例添加截图,请建议我在哪里进行修改。

selenium logging appium screenshot extentreports
1个回答
0
投票

要在Extent Reports中为失败的测试添加截图,使用下面的代码。

@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;
}

希望对你有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.