5

I'm trying to add a screenshot to my ExtentReport HTML file, but for some reason, the image is not there even though it DOES exist and the console shows that it's looking at the correct place (href is correct).

This is the latest trial code:

Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
String destination = getScreenshotPath();
ImageIO.write(screenshot.getImage(), "IMG", new File(destination));
test.fail("Details: " + test.addScreenCaptureFromPath(destination));

The screenshot gets saved in the destination. When I try the debugging mode, or look at the report, it's printed as:

Details: com.aventstack.extentreports.ExtentTest@62041567 and there's a broken image under it:

enter image description here

9 Answers 9

6

As suggested - the absolute path could be a solution, but I didn't want to go that way.

I've figured out that a solution is to store the images in the same directory where the report gets generated, give the image name to .addScreenCaptureFromPath(screenshotName.PNG) and it works perfectly.

3
  • 1
    This does not solve the issue, at least not in my case. Oct 16, 2019 at 9:03
  • What if you run several tests in the same suite and it would be multiple failures with screenshot for each failure?
    – Prophet
    Dec 22, 2020 at 18:13
  • This worked for me. Please note that it is not required to keep the report and screenshot in the same folder. Feb 13 at 9:55
5

I used the absolute path

Note: inspects the broken image from the browser to validate the absolute path of the image

Take ScreenShot:

  public static String TakesScreenshot(IWebDriver driver, string FileName)
    {

        string pathProject = AppDomain.CurrentDomain.BaseDirectory;
        string pathScreen = pathProject.Replace("\\bin\\Debug", "");
        string path = pathScreen + "project/Test-output/Images/";

        StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
        TimeAndDate.Replace("/", "_");
        TimeAndDate.Replace(":", "_");
        TimeAndDate.Replace(" ", "_");

        string imageName = FileName + TimeAndDate.ToString();

        ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(path + "_" + imageName + "." + System.Drawing.Imaging.ImageFormat.Jpeg);

        return path + "_" + imageName + "." + "jpeg";
    }

Attach image to the report with path of the preview method: In the specific step:

ExtentTest.Fail("message", MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.TakesScreenshot(driver, "Fatal")).Build());

With the method "TakesScreenshot" Take the screenshot

Version ExtentReport: 3, C#, NUnit 3

USING JAVA:

        <dependency>
        <groupId>com.relevantcodes</groupId>
        <artifactId>extentreports</artifactId>
        <version>2.41.2</version>
        </dependency>

Is:

 ExtentTestManager.getTest().log(LogStatus.ERROR, ExtentTestManager.getTest().addScreenCapture("//ABOLUTE/PATH/IMAGE.PNG"));

regards.

2

In order to get screenshot in the extent report just add a extra dot in the extent report screenshot path. Refer code below:

test.log(Status.INFO, "FAQs button clicked",
                        MediaEntityBuilder.createScreenCaptureFromPath("." + screenshot()).build());

Hope this helps!

0
1

You can add screenshot for absolute path as below:

File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

//for file copy, absolute path starts from your project directory

FileUtils.copyFile(src, new File("../resources/reports/screenshots/screen2.png"));

String img = logger.addScreenCapture("./screenshots/screen2.png");

logger.log(LogStatus.PASS, "Title verified...", img);

Please note that here in addScreenCapture() method path started from screenshots folder and not resources as in copyFile() method. Its because ExtentReports is initialized as :

ExtentReports report = new ExtentReports("../resources/reports/extentreports_v2.html", true);

so for extentreports_v2.html to find screenshot's absolute path, it should start from "reports" directory

1
  • Your solution works for me like a charm. Thanks!
    – Kamil
    Apr 19, 2022 at 7:55
0

This is will work for you as its works me as well.

public void afterScenario(Scenario scenario) throws IOException {
        if (scenario.isFailed()) {
            String screenshotName = scenario.getName().replaceAll(" ", "_");
            //This takes a screenshot from the driver at save it to the specified location
            File sourcePath = ((TakesScreenshot) testContext.getWebDriverManager().getDriver()).getScreenshotAs(OutputType.FILE);

            //Building up the destination path for the screenshot to save
            //Also make sure to create a folder 'screenshots' with in the cucumber-report folder
            File destinationPath = new File("./src/test/resources/"+screenshotName + ".png");

            //Copy taken screenshot from source location to destination location
            Files.copy(sourcePath, destinationPath);

            //This attach the specified screenshot to the test
            Reporter.addScreenCaptureFromPath(screenshotName+".png");
            System.out.println("Cant take screenshot in grid.");
        }
    }
0

I tried various sites and blogs for this issue, but couldn't get a solution anywhere. I got below solution after trying various approaches. Try the below solution and it worked perfectly for me.

public static synchronized String addScreenshots(){
     WebDriver webDriver = Browser.getDriver();
     Long l = Calendar.getInstance().getTimeInMillis();
     String screenshotId = l.toString();
     String Path = System.getProperty("user.dir")+"/ExtentReports/"; 

     File screenshot = ((TakeScreenshot)WebDriver).getScreenshotAs(OutputType.FILE);
     String imgPath = Path+screenshotId+".png";
     
     File dest = new File(imgPath);
     try {
         FileUtils.copyFile(screenShot, dest);
     } catch (IOException e) {
         e.printStackTrace();
     }
     
     String ImagePath = "../ExtentReports/"+screenshotId+".png";
     
     return ImagePath;
}
2
  • Can you a bit clarify about Path in String imgPath = Path+screenshotId+".png";?
    – Yeheshuah
    May 25, 2021 at 0:20
  • In the above code, Path = System.getProperty("user.dir")+"/ExtentReports/";
    – DMac
    May 27, 2021 at 2:51
0

I tried the following code, and it resulted in a screenshot being recorded in the report.

File file = new File("./Screenshots/" + result.getName() + ".png");

String absolutePath = file.getAbsolutePath();
logger.fail("details", MediaEntityBuilder.createScreenCaptureFromPath(absolutePath).build());
1
  • 1
    are you sure it is solving the issue, if it resulted the same error? Feb 8, 2022 at 14:15
0

The below piece of code can solve your problem:

public void reportStatus(ITestResult result){
 if(result.getStatus()==ITestResult.FAILURE){
 
     String screenshotFilePath=takeScreenshotMethod(driver, result.getName());
     extentTest.log(Status.FAIL, "Screenshot", MediaEntityBuilder.createScreenCaptureFromPath(screenshotFilePath).build());
 }
}
0
 public static void TakeScreenshot(Status status, string stepDetail)
        {
            string path = @"C:\ExtentReports\" + "TestExecLog_" + DateTime.Now.ToString("yyyyMMddHHmmss");

            Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
            image.SaveAsFile(path + ".png", ScreenshotImageFormat.Png);
            ExtentReport.exChildTest.Log(status, stepDetail, MediaEntityBuilder.CreateScreenCaptureFromPath(path + ".png").Build());
        
    }

        public static void ReadJsonObject(string filename)
        {
            string myJsonString = File.ReadAllText(@"..\\..\\..\\" + filename);
            jobject = JObject.Parse(myJsonString);
            
        }

        public static void ReadJsonArray(string filename)
        {
            string myJsonString = File.ReadAllText(@"..\\..\\..\\" + filename);
            jarray = JArray.Parse(myJsonString);
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.