7
votes

I am looking for a way to attach a screenshot to Results section of TestNG Report for the failed methods.

So far I was able to attache my screenshots to Reporter Output by implementing this:

Reporter.log("<br> <img src=.\\screenshots\\" + fileName + " /> <br>");

but still struggling with adding them to Test Results section of failed methods.

I was able to implement Listener and intercept onTestFailure actions which was originally suggested here: How can I include a failure screenshot to the testNG report

Here is an example of that:

    @Override
public void onTestFailure(ITestResult result) { 
    Reporter.setCurrentTestResult(result); 
    Reporter.log("<br> <img src=.\\screenshots\\Untitled.png /> <br>");
    Reporter.setCurrentTestResult(null); 
}

But Reporter.log function still pushes my information in the Reporter output log but not in the Results->Failed methods->Failed method log.

Update (03/14/14): I've attached screenshot to clarify my question. The problem is not in capturing screenshot and attaching it to Report. That part works fine. The problem is that screenshot is attached to Test Output part of the report but I want to see it in Results -> Failed Methods.

enter image description here

8

8 Answers

0
votes

I have also implemented the same extending Testng TestListenerAdapter. By capturing the screenshot then attach it to the Testng Report with the image of size height=100 and width=100 with onTestFailure. Please see below if this helps solve your problem

    File scrFile = ((TakesScreenshot) WebdriverManager.globalDriverInstance).getScreenshotAs(OutputType.FILE);
      //Needs Commons IO library
      try {
        FileUtils.copyFile(scrFile, new File(file.getAbsolutePath()+ "/selenium-reports/html/" + result.getName() + ".jpg"));
        Reporter.log("<a href='"+ file.getAbsolutePath()+"/selenium-reports/html/" + result.getName() + ".jpg'> <img src='"+ file.getAbsolutePath()+"/selenium-reports/html/"+ result.getName() + ".jpg' height='100' width='100'/> </a>");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Reporter.setCurrentTestResult(null);
0
votes

In addition to above don't forget to add following lines to your testng suite xml

<listeners>
    <listener class-name="com.tests.DotTestListener" />
</listeners>

OR

passing as listner parameter if you are executing it from command line

java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener com.tests.DotTestListener test\testng.xml

Reference : http://testng.org/doc/documentation-main.html#logging-listeners

0
votes

I've had same problem but it solved. By implementing SuitePanel you will be able to add screenshot as you want https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/jq/SuitePanel.java

I almost don't change the original code except

... 
// Description?
String description = tr.getMethod().getDescription();
if (! Strings.isNullOrEmpty(description)) {
    xsb.push("em");
    xsb.addString("(" + description + ")");
    xsb.pop("em");
}
// Add screen shot here
xsb.push(“img”,”src”,imagePath);
xsb.pop(“img”);

xsb.pop(D);
xsb.pop(D);
0
votes

If you want to show the screen shot on the failed method then you will have to capture the exception and modify its message content and add img html to that and then it will appear. Let me know if you need example

0
votes

I had same issue but its fixed now. I made a method to catcher screenshot in base class. this method return full path of screenshot.

public String getScreenshot (String screenshotName, WebDriver driver) throws IOException{
    DateFormat dateformate = new SimpleDateFormat("dd-mm-yy-hh-mm-ss");
    Date date = new Date();
    String currentdate = dateformate.format(date);
    String imageName =screenshotName+currentdate;
    TakesScreenshot ts=(TakesScreenshot)driver;
    File source=ts.getScreenshotAs(OutputType.FILE);
    String location =System.getProperty("user.dir")+"\\testOutput\\screenshot\\"+imageName+".png";
    File screenshotLocation =new File (location);
    FileUtils.copyFile(source, screenshotLocation);
    return location;

}

Add use this path to add screenshot in testng report as well as report log by updating testng TestNgListener-

public void onTestFailure(ITestResult arg0) {
    Object currentClass = arg0.getInstance();
    WebDriver driver = ((BrowserSetup) currentClass).getDriver();
    String name = arg0.getName();
    System.out.println(name);
    try {
        String screenshotPath =getScreenshot(name, driver);
        System.out.println("Screenshot taken");
        String path = "<img src=\"file://" + screenshotPath + "\" alt=\"\"/>";
        System.out.println(screenshotPath+" and path - "+path);
        Reporter.log("Capcher screenshot path is "+path);
    } catch (Exception e) {
        System.out.println("Exception while takescreenshot "+e.getMessage());
    }
    printTestResults(arg0);

}

enter image description here

0
votes

I suggest you to use ReportNG instead of the primitive TestNG reports.

0
votes

If the problem only with getting screenshots, you can try to get it like this:

private static byte[] GetCropImg(IWebDriver targetChrome, IWebElement targetElement)
        {
            var screenshot = ((ITakesScreenshot)targetChrome).GetScreenshot();
            var location = targetElement.Location;
            using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
            {
                var rect = new Rectangle(location.X, location.Y, targetElement.Size.Width, targetElement.Size.Height);
                using (Bitmap bmpImage = new Bitmap(stream))
                {
                    using (Bitmap cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            cropedImag.Save(ms, ImageFormat.Jpeg);

                            byte[] byteImage = ms.ToArray();
                            return byteImage;
                        }
                    }
                }
            }
        }

and then you can save file or save sting64

var imgString64 = Convert.ToBase64String(byteImage); //Get Base64

PS: on JAVA it should be almost the same)

0
votes

enter image description hereyou can get failed test cases screen shots with name of failed test class by using @After method. Use below code segment enter image description here