简体   繁体   English

如何将屏幕截图附加到 java selenium 中的范围报告

[英]How to attach screenshot to Extent Report in java selenium

I am trying to attach screenshot for failed testcases from my path to Extent Report but somehow i am not able to attach into it.我正在尝试从我的路径到范围报告的路径中附加失败测试用例的屏幕截图,但不知何故我无法附加到其中。

I have tried my possible solution but it fails.我已经尝试了我可能的解决方案,但它失败了。 I have used extent report version 3我使用了范围报告版本 3

here is mine full code in separate extenreport class:这是我在单独的 extenreport class 中的完整代码:

    package com.qa.ExtentReportListener;


    import java.io.IOException;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;

    import org.testng.IReporter;
    import org.testng.IResultMap;
    import org.testng.ISuite;
    import org.testng.ISuiteResult;
    import org.testng.ITestContext;
    import org.testng.ITestResult;
    import org.testng.Reporter;
    import org.testng.xml.XmlSuite;

    import com.aventstack.extentreports.ExtentReports;
    import com.aventstack.extentreports.ExtentTest;
    import com.aventstack.extentreports.Status;
    import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
    import com.aventstack.extentreports.reporter.configuration.ChartLocation;
    import com.aventstack.extentreports.reporter.configuration.Theme;
    import com.crm.qa.util.TestUtil;

    public class ExtentTestNGIReporterListener implements IReporter {

        private static final String OUTPUT_FOLDER = "test-output/";
        private static final String FILE_NAME = "Extent.html";

        private ExtentReports extent;
        private ExtentTest test;

        public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
            init();

            for (ISuite suite : suites) {
                Map<String, ISuiteResult> result = suite.getResults();

                for (ISuiteResult r : result.values()) {
                    ITestContext context = r.getTestContext();

                    buildTestNodes(context.getFailedTests(), Status.FAIL);
                    buildTestNodes(context.getSkippedTests(), Status.SKIP);
                    buildTestNodes(context.getPassedTests(), Status.PASS);

                }
            }

            for (String s : Reporter.getOutput()) {
                extent.setTestRunnerOutput(s);
            }

            extent.flush();
        }

        private void init() {
            ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
            htmlReporter.config().setDocumentTitle("ExtentReports - Created by TestNG Listener");
            htmlReporter.config().setReportName("ExtentReports - Created by TestNG Listener");
            htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
            htmlReporter.config().setTheme(Theme.STANDARD);

            extent = new ExtentReports();
            extent.attachReporter(htmlReporter);
            extent.setReportUsesManualConfiguration(true);
        }

        private void buildTestNodes(IResultMap tests, Status status) {


            if (tests.size() > 0) {
                for (ITestResult result : tests.getAllResults()) {
                    test = extent.createTest(result.getMethod().getMethodName());

                    for (String group : result.getMethod().getGroups())
                        test.assignCategory(group);

                    if (result.getThrowable() != null) {
                        test.log(status, result.getThrowable());
                    }
                    else {
                        test.log(status, "Test " + status.toString().toLowerCase() + "ed");
                    }

                    test.getModel().setStartTime(getTime(result.getStartMillis()));
                    test.getModel().setEndTime(getTime(result.getEndMillis()));
                }
            }
        }

        public void down(ITestResult result) throws IOException{


            if(result.getStatus()==ITestResult.FAILURE){
                test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getName()); //to add name in extent report
                test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getThrowable()); //to add error/exception in extent report

                String screenshotPath = TestUtil.takeScreenshotAtEndOfTest();
                test.fail("Test Case failed check screenshot below"+test.addScreenCaptureFromPath(screenshotPath));
                //extentTest.log(Status.FAIL, MediaEntityBuilder.createScreenCaptureFromPath(screenshotPath).build()); //to add screenshot in extent report
                //extentTest.fail("details").addScreenCaptureFromPath(screenshotPath);
            }
            else if(result.getStatus()==ITestResult.SKIP){
                test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
            }
            else if(result.getStatus()==ITestResult.SUCCESS){
                test.log(Status.PASS, "Test Case PASSED IS " + result.getName());

            }
        extent.flush();
        }

        private Date getTime(long millis) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(millis);
            return calendar.getTime();      
        }
    }

here is my util class which contain screenshot method:这是我的工具 class ,其中包含截图方法:

public static String takeScreenshotAtEndOfTest() throws IOException {
    String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
    TakesScreenshot ts = (TakesScreenshot)driver;
    File source = ts.getScreenshotAs(OutputType.FILE);
    String destination = System.getProperty("user.dir") + "/screenshots/" +  dateName
            + ".png";
    File finalDestination = new File(destination);
    FileHandler.copy(source, finalDestination);
    return destination;
}

If you want take screen shots for failed test cases with test class name use below code segment.如果您想使用测试 class 名称为失败的测试用例截屏,请使用下面的代码段。

点击这里

在此处输入图像描述

Extent Report already provide the utility to take the screenshot.Please refer the below link:范围报告已经提供了截图的实用程序。请参考以下链接:

https://extentreports.com/docs/versions/3/java/#automatic-screenshot-management https://extentreports.com/docs/versions/3/java/#automatic-screenshot-management

also find the snapshot and code for same:还可以找到相同的快照和代码:

 ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
htmlReporter.config().setAutoCreateRelativePathMedia(true);

test1.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("1.png").build());
test2.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("2.png").build());

how to take Screenshot using extent report如何使用范围报告截屏

Try using this:尝试使用这个:

logger.log(Status.FAIL, logger.addScreenCaptureFromPath("YOUR PATH"));

UPDATE: If this doesn't work, just cast the inner logger with markup.更新:如果这不起作用,只需使用标记转换内部记录器。 import com.aventstack.extentreports.markuputils.Markup;导入 com.aventstack.extentreports.markuputils.Markup;

    package com.helper;

    import org.testng.annotations.Test;

    import com.aventstack.extentreports.AnalysisStrategy;
    import com.aventstack.extentreports.ExtentReports;
    import com.aventstack.extentreports.ExtentTest;
    import com.aventstack.extentreports.MediaEntityBuilder;
    import com.aventstack.extentreports.Status;

    import com.aventstack.extentreports.reporter.ExtentSparkReporter;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;

    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.By;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.edge.EdgeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.opera.OperaDriver;
    import org.testng.IResultMap;
    import org.testng.ITest;
    import org.testng.ITestContext;
    import org.testng.ITestResult;
    import org.testng.Reporter;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Listeners;
    import org.testng.annotations.Test;







    public class TestingEdgeDriver {
        ExtentReports extent;
        ExtentTest test;
        WebDriver driver;
        ExtentTest Parent;
        ExtentTest child1,child;
        
        @BeforeMethod
        public void setup(){
            
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH-mm-ss"); 
            String destDir = dateFormat.format(new Date());
            ExtentSparkReporter esp=new ExtentSparkReporter(System.getProperty("user.dir")+"/ExtentReport/ExtentReports_"+destDir+"/SwarupExtentReport.html");
            extent=new ExtentReports();
            extent.attachReporter(esp);
            extent.setAnalysisStrategy(AnalysisStrategy.SUITE);
        }
        
        @Test (testName="Chrome browser Testing")public void chromeBrowser() throws IOException{
            /*extent.attachReporter(spark);
            extent.createTest("chromeBrowser").log(Status.PASS  , "This is logging event for the setup and it is passed");
            extent.flush();*/
            Parent=extent.createTest("CMO");
            child1=Parent.createNode("Test1");
            child=child1.createNode("Chrome browser Testing");
            
            System.out.println("The tread value for Chrome browser is "+ Thread.currentThread().getId());
            System.setProperty("webdriver.chrome.driver","E:\\chromedriver_win32 (2)\\chromedriver.exe");
            driver=new ChromeDriver();
            child.log(Status.PASS, "Chrome browser has opened",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
            driver.get("https://www.icicibank.com");
            
            child.log(Status.PASS,"Expected was its should open the bank website",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
            
            child.log(Status.PASS, "Need to open the URL "+" http://www.icicibank.com");
            driver.manage().window().maximize();
            child.log(Status.PASS, "Test Case is passed",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
            
            
            
        }
        
        @AfterMethod
        public void getResult(ITestResult result){
            if(result.getStatus()==ITestResult.SUCCESS){
                child.log(Status.PASS, "Test case is passed "+result.getStatus()+" "+result.getTestClass()+"  "+result.getName());
                child.log(Status.PASS, "Test case is passed "+result.getTestName());
                
            }
            if(result.getStatus()==ITestResult.FAILURE){
                child.log(Status.FAIL, "Test case is failed at below location "+result.getThrowable());
            }
            extent.flush();
        }
        
        
        /*@Test public void operaTesting(){
            System.out.println("The tread value for Opera browser is "+ Thread.currentThread().getId());
            System.setProperty("webdriver.opera.driver","E:\\operadriver_win32\\operadriver_win32\\operadriver.exe");
            Reporter.log("opera driver has been set",true);
            driver=new OperaDriver();
            driver.manage().window().maximize();
            driver.get("https://www.irctc.co.in");
        }
        @Test public void FirefoxTesting(){
            System.out.println("The tread value for Firefox browser is "+ Thread.currentThread().getId());
            System.setProperty("webdriver.gecko.driver","E:\\gecodriver\\geckodriver-v0.29.0-win32\\geckodriver.exe");
            Reporter.log("Gecko Driver has been set",true);
            driver=new FirefoxDriver();
            driver.manage().window().maximize();
            Reporter.log("firefox driver has been initialsed",true);
            driver.get("https://www.primevideo.com/");
        }
        @Test public void InternetExplorerTesting(){
            System.out.println("The tread value for IE browser is "+ Thread.currentThread().getId());
            System.setProperty("webdriver.ie.driver","E:\\IEDriverServer_Win32_3.4.0\\IEDriverServer.exe");
            Reporter.log("IE driver has been set",true);
            driver=new InternetExplorerDriver();
            driver.manage().window().maximize();
            driver.get("https://www.hotstar.com/in");
        }*/
        
        public static String captureBase64(WebDriver driver) throws IOException {
            String encodedBase64 = null;
            FileInputStream fileInputStream = null;
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
            + ".png");
            String errflpath = Dest.getAbsolutePath();
            FileUtils.copyFile(scrFile, Dest);
             
            try {
                
                fileInputStream =new FileInputStream(Dest);
                byte[] bytes =new byte[(int)Dest.length()];
                fileInputStream.read(bytes);
                encodedBase64 = new String(Base64.encodeBase64(bytes));

            }catch (FileNotFoundException e){
                e.printStackTrace();
            }
            return "data:image/png;base64,"+encodedBase64;
            
            
            }
        
        public static String capture(WebDriver driver) throws IOException {
            
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
            + ".png");
            String errflpath = Dest.getAbsolutePath();
            FileUtils.copyFile(scrFile, Dest);
            return errflpath;
            }
    }

Use this code in after method在 after 方法中使用此代码

if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) { String screenshotPath = util.captureScreenshot(driver, result.getName()); if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) { String screenshotPath = util.captureScreenshot(driver, result.getName()); result.setAttribute("screenshotPath", screenshotPath); result.setAttribute("screenshotPath", screenshotPath); //sets the value the variable/attribute screenshotPath as the path of the sceenshot } //将变量/属性screenshotPath的值设置为sceenshot的路径}

and add below code in buildtestnodes并在 buildtestnodes 添加以下代码

if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) {
                    String screenshotPath=(String) 
 result.getAttribute("screenshotPath");
                    test.log(status, test.addScreenCapture(screenshotPath));
                } 

Use this following example is in Java使用以下示例在 Java

   WebDriver driver = new FirefoxDriver();

   driver.get("http://www.google.com/");

        // Store the screenshot in current project dir.
        String screenShot = System.getProperty("user.dir")+"\\Artifacts\\FileName.png";

        // Call Webdriver to click the screenshot.
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // Save the screenshot.
        FileUtils.copyFile(scrFile, new File(screenShot));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将屏幕截图附加到 cucumber java 中的范围报告 - How to attach screenshot to extent report in cucumber java 如何使用 selenium 4 和 java 编写通用的 base64 截图方法并将其附加到测试失败的范围报告中? - How to write a generic base64 screenshot method using selenium 4 with java and attach it to extent report on test failure? 如何将屏幕截图附加到 azure 报告 selenium java Z1441F19754330CA4638BFDFAZEA - How to attach screenshot to azure report for selenium java cucumber Cucumber 范围报告 - 如何将失败案例的屏幕截图添加到范围报告 - Cucumber extent report - how to add screenshot of failed case to the extent report 范围报告3添加屏幕截图 - Extent Report 3 Add Screenshot 无法在Selenium Java中生成范围报告 - Unable to generate Extent Report in Selenium Java 如何在诱惑报告中附加自定义/现有屏幕截图? - How to attach custom/existing screenshot in allure report? 无法在Selenium Java中的范围报告中合并多个类 - Unable to merge multiple classes in Extent Report in selenium java 无法将屏幕截图添加到 Cucumber 中的范围报告 - Not able to add the screenshot to the extent report in Cucumber 如何在使用 Cucumber 和 JUnit 时截屏并将其附加到 Allure 报告中? - How take screenshot and attach it to Allure report, while using Cucumber and JUnit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM