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

StopTheRain
  • 367
  • 1
  • 5
  • 15

9 Answers9

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.

StopTheRain
  • 367
  • 1
  • 5
  • 15
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!

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

pravinb
  • 31
  • 2
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.");
        }
    }
Sobhit Sharma
  • 697
  • 14
  • 45
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;
}
DMac
  • 1
  • 1
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());
The Mighty Programmer
  • 1,242
  • 12
  • 23
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());
 }
}
cigien
  • 57,834
  • 11
  • 73
  • 112
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);
        }